0

I am really trying to get my head round collision detection, here are my game details: I have a character that can move freely around the screen and fire bullets Enemies are generated off screen and the ‘hero’ can shoot them (when bullets and enemies are created they are stored in arrays and then removed at collision) Currently if the enemy makes contact with the hero then nothing happens, I would like a life to be removed on contact and believe this is done via collision detection. I am using

(CGRectIntersectsRect([hero boundingBox], [enemy boundingBox])) 

But not all collisions are detected and then suddenly 3 will detected. I believe that this is caused as multiple collisions are detected as the objects pass through each other. I have tried to use a BOOL flag to but I don’t believe that I am doing it correctly, my code:

.h
BOOL collision;
.m
-(void)update:(ccTime)deltaTime {    
    if (collision == NO) {
        if (CGRectIntersectsRect([hero boundingBox], [enemy boundingBox])) {
            CCLOG(@”collision detected!!!!!!!!!!!!!!!!”);
            collision = YES;
        }
    }
} 

Is this the best way to deal with collision detection and if so how do you implement the BOOL flag?

4

2 回答 2

1

您只需在碰撞时将布尔值设置为是,在停止碰撞时将布尔值设置为否,以便下次知道什么时候是新的碰撞。

if (CGRectIntersectsRect([hero boundingBox], [enemy boundingBox])) {
    CCLOG(@”collision detected!!!!!!!!!!!!!!!!”);
    if(!collision) {
        // REMOVE LIFE
    }
    collision = YES;
}
else {
    collision = NO;
}
于 2013-08-14T07:34:38.843 回答
0

为你的敌人对象创建一个 bool 属性,并在敌人的 init 方法上将其设置为 false。当检测到碰撞时,将其值设置为 true 并在您的更新方法中检查如下内容:

if (enemy.isCollide)
 {
    if (!CGRectIntersectsRect([hero boundingBox], [enemy boundingBox])) 
    {
       enemy.isCollide = No;
    }
 }
else
 {
    if (CGRectIntersectsRect([hero boundingBox], [enemy boundingBox])) {
    enemy.isCollide = Yes; }
 } 
于 2013-08-14T08:08:04.650 回答