您好我正在制作一个cocos2d侧卷轴。我试图测试两个精灵之间的碰撞。我检查过,我为精灵制作的作品是它们应该是什么,但是它说这两个部分一直相交,无论它们是否真的如此。这是代码:
-(void)checkForRedEnemyCollisions{
CGRect playerRect = CGRectMake(player.position.x - (player.playerSprite.contentSize.width/2),
player.position.y - (player.playerSprite.contentSize.height/2),
player.playerSprite.contentSize.width,
player.playerSprite.contentSize.height);
CGRect redEnemyRect = CGRectMake(redEnemy.position.x - (redEnemy.bulletSprite.contentSize.width / 2) ,
redEnemy.position.y - (redEnemy.bulletSprite.contentSize.height /2 ),
redEnemy.bulletSprite.contentSize.width,
redEnemy.bulletSprite.contentSize.height);
if (CGRectIntersectsRect(playerRect, redEnemyRect)) {
CCLOG(@"collision");
}
}
这是更多代码:
-(id)init{
if((self = [super init])){
CGSize size = [[CCDirector sharedDirector]winSize];
screenWidth = size.width;
screenHeight = size.height;
gravity = 2;
playerSprite = [CCSprite spriteWithFile:@"thefinalcharacter.png"];
playerSprite.scale = 1.5;
playerSprite.position = ccp(screenWidth/3.4, screenHeight/2);
[self addChild:playerSprite z:-3];
[self schedule: @selector(flight:)interval:1.0f/7.0f];
}
return self;
}
-(void)flight:(ccTime)delta{
flightCounter ++;
if (flightCounter % 2){
[playerSprite setTexture:[[CCSprite spriteWithFile:@"thefinalcharacter.png"]texture]];
}else{
[playerSprite setTexture:[[CCSprite spriteWithFile:@"thefinalcharacter2.png"]texture]];
}
[self schedule:@selector(updatePosition:)interval:1.0f/30.0f];
}
-(void)updatePosition:(ccTime)delta{
if(playerSprite.position.y < 35){
gravity = 0;
}else if(playerSprite.position.y > screenHeight - 150) {
playerSprite.position = ccp(playerSprite.position.x, playerSprite.position.y - 100);
}else{
gravity = 2;
}
playerSprite.position = ccp(playerSprite.position.x, playerSprite.position.y - gravity);
}
答案 0 :(得分:0)
确保您在世界坐标中创建边界矩形。
尝试将点转换为世界坐标,如下所示;
CGPoint playerWorldPosition = [player ConvertToWorldSpace:player.position];
CGRect playerRect = CGRectMake(playerWorldPosition.x - (player.playerSprite.contentSize.width/2),
playerWorldPosition.y - (player.playerSprite.contentSize.height/2),
player.playerSprite.contentSize.width,
player.playerSprite.contentSize.height);
为redEnemy做同样的事情。这将确保您在世界空间中比较它们,而不是在层次结构中的另一个空间中进行比较。
如果您在播放器或redEnemies上使用锚点而不是默认值(0.0,0.0)。使用ConvertToWorldSpaceAR函数而不是ConvertToWorldSpace。