你好堆栈溢出的人 我今天站在你面前,有一个(不是很好的)cocos2d问题。
如何在动作中检查WHILE中的碰撞,而不是检查目标图块? 我正在使用一个tilemap,它有一个meta层,其中有可碰撞的tile。单击可碰撞的图块时,下面的代码可以正常工作,但是当我点击它时,它不会发生,如果发生这种情况,他将直接走过。
目前,我检测到与此代码的冲突:
-(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
运行时,如何不断检查可碰撞元图块的碰撞?
答案 0 :(得分:0)
在初始化中,安排碰撞检测方法:
[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;
}
}
}
}
答案 1 :(得分:-1)
我使用了类似的元图层。我个人跳过使用MoveTo,并创建了自己的更新代码,既可以移动精灵也可以进行碰撞检测。
我弄清楚潜在的新位置会是什么,然后我会发现在新位置的精灵的所有四个角落中有什么平铺位置,然后我循环遍历精灵所在的所有平铺,如果有的话可以碰撞,我停止精灵。
我实际上更进了一步,检查是否仅移动x,或仅移动y更改结果,然后移动到该位置(如果是的话)。