2011-11-05 66 views
0

好吧,我最后一次尝试了这个,它太模糊,所以我会再试一次。我正在制作一个自上而下的透视iPhone游戏,有一个mainSprite(一个UIImageView),它将与另一个UIImageView相冲突。当它发生时,我希望mainSprite停止移动。基本上创造一堵墙。那有意义吗?我没有使用任何框架,如cocos2d。我知道CGRectIntersectWithRect方法,我的问题是我需要在该方法中放置什么。我没有任何其他变量,例如速度或速度,只是会在屏幕上移动精灵的按钮。这是我的代码。iPhone游戏开发,碰撞检测,创造了墙效应

这是用于在屏幕上移动精灵的.m代码。

-(void)goDown{ 
mainSprite.center = CGPointMake(mainSprite.center.x, mainSprite.center.y+5); 
} 

-(IBAction)down{ 
    [self downAnimation]; 
    goDown = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(goDown) userInfo:nil repeats:YES]; 
    if (goDown == nil) { 
     goUp = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(goDown) userInfo:nil repeats:YES]; 

    } 
} 

这里是我已建立了碰撞的方法:

-(void)collision { 
    if (CGRectIntersectsRect(mainSprite.frame, collisionImage.frame)) { 

    } 
} 

帮助将不胜感激。

回答

1

你可以做什么是添加上的对象是否已经相撞布尔(我建议作为一个实例变量)

有了这个当rects有相交

,你可以将它设置为YES在您的仓库方法,你会再查布尔,如果布尔为是,则不会改变中心,否则继续改变它

每次-goDown被称为添加在检查碰撞

这样,如果它已经发生了碰撞,你可以实际上停用该定时器,使其不再停机,或者你可以按照上面提到的布尔方式来实现。

我建议作出与当前中心的一个论据碰撞检查方法,以便您可以检查是否将5与中心的y会使其发生碰撞,因此您可以禁用定时器/停止加5正确的,因为它发生碰撞,而不是之后

- (void)goDown { 
    float delta = [self checkCollision]; 
    mainSprite.center = CGPointMake(mainSprite.center.x, mainSprite.center.y + delta); 
} 

- (float)checkCollision { 
    CGRect testFrame = CGRectMake(mainSprite.frame.origin.x, mainSprite.frame.origin.y + 5.0f, mainSprite.frame.size.width, mainSprite.frame.size.height); 
    if (CGRectIntersectsRect(testFrame, collisionImage.frame)) { 
     return 0.0f; 
     // stop the sprite from moving anymore so it doesn't actually intersect, just stops "on top" 
    } 
    return 5.0f; 
    // if they have not collided then just continue on your way 

的代码示例实际显示没有我的方法上面

什么,我在这里做的是检查是否有冲突,如果那里有将要发生碰撞,然后停止添加任何到中心,否则它会继续添加到中心坐标

+0

这很有道理,但你能告诉我如何重置mainSprite位置到其他UIImageView之外吗? –

+0

你的意思是在另一个之外? – DanZimm

+0

就像mainSprite与UIImageView相撞时,我需要写什么代码才能将mainSprite保留在UIImageView之外,从而创建墙效果? –