0

你好堆栈溢出的好人我今天站在你面前有一个(不是很好)cocos2d 问题。

如何在动作中检查碰撞,而不是检查目标图块?我正在使用具有元图层的瓷砖地图,其中有可碰撞的瓷砖。以下代码在我单击可碰撞瓷砖时有效,但当我单击超出它时无效,如果发生这种情况,他将直接穿过。

目前,我检测到与此代码的冲突:

-(void)setPlayerPosition:(CGPoint)position {
CGPoint tileCoord = [self tileCoordForPosition:position];
int tileGid = [_meta tileGIDAt:tileCoord];
if (tileGid) {
    NSDictionary *properties = [_tileMap propertiesForGID:tileGid];
    if (properties) {
        NSString *collision = properties[@"Collidable"];
        if (collision && [collision isEqualToString:@"True"]) {
            return;
        }
    }
}

float speed = 10;
CGPoint currentPlayerPos = _player.position;
CGPoint newPlayerPos = position;
double PlayerPosDifference = ccpDistance(currentPlayerPos, newPlayerPos) / 24;
int timeToMoveToNewPostition = PlayerPosDifference / speed;
id moveTo = [CCMoveTo actionWithDuration:timeToMoveToNewPostition position:position];
[_player runAction:moveTo];

//_player.position = position;
}

顺便说一句,这是从此方法调用的:

-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
[_player stopAllActions];
CGPoint touchLocation = [touch locationInView:touch.view];

touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];

CGPoint playerPos = _player.position;
CGPoint diff = ccpSub(touchLocation, playerPos);

int diffx = diff.x;
int diffy = diff.y;
int adiffx = diffx / 24;
int adiffy = diffy / 24; //Porque my tile size is 24     

if ( abs(diff.x) > abs(diff.y) ) {
    if (diff.x > 0) {
        playerPos.x = playerPos.x + adiffx * 24;
    } else {
        playerPos.x = playerPos.x + adiffx * 24;
    }
} else {
    if (diff.y > 0) {
        playerPos.y = playerPos.y + adiffy * 24;
    }else{
        playerPos.y = playerPos.y + adiffy * 24;
    }
}
[self setPlayerPosition:playerPos];
}

我试过

    [self schedule:@selector(setPlayerPosition:) interval:0.5];

没有任何运气,这只是立即使应用程序崩溃

NSAssert( pos.x < _layerSize.width && pos.y < _layerSize.height && pos.x >=0 && pos.y >=0, @"TMXLayer: invalid position"); 我真的不能责怪它在那里崩溃。

如何在CCMoveTo运行时不断检查与可碰撞元图块的碰撞?

4

2 回答 2

0

在您的 init 中,安排一个碰撞检测方法:

[self schedule:@selector(checkCollisions:)];

然后定义如下:

-(void)checkCollisions:(ccTime)dt
{
    CGPoint currentPlayerPos = _player.position;
    CGPoint tileCoord = [self tileCoordForPosition:currentPlayerPos];
    int tileGid = [_meta tileGIDAt:tileCoord];
    if (tileGid) 
    {
        NSDictionary *properties = [_tileMap propertiesForGID:tileGid];
        if (properties) 
        {
            NSString *collision = properties[@"Collidable"];
            if (collision && [collision isEqualToString:@"True"]) 
            {
                [_player stopAllActions];
                return;
            }
        }
    }
}
于 2013-04-25T17:38:01.000 回答
-1

我使用类似的元层。我个人跳过了使用 MoveTo,并创建了自己的更新代码,既可以移动精灵又可以进行碰撞检测。

我找出潜在的新位置是什么,然后找出新位置的精灵的所有四个角中的瓷砖位置,然后循环遍历精灵将在的所有瓷砖,如果有的话,我停止精灵。

实际上,我更进一步检查是否仅移动 x,或者仅移动 y 更改结果,然后移动到该位置而不是移动到该位置。

于 2013-04-25T15:23:43.163 回答