Search code examples
iosobjective-ccocos2d-iphonegame-physicsspritebuilder

Sometimes sprite is pushed away when touches another sprite


I am making a game using cocos2d and SpriteBuilder. There is a hero sprite and coins, that should be collected by him. That's a horizontal scrolling game, so every time hero touches a coin, this coin changes it's x-coordinate 2000px to the right and new y-coordinate is generated at random. Using update method I move it to the visible area as a "new" coin. But when hero flyies by and doesn't collect it ,coin must change coordinates only when it's already off the screen, so I tried this solution:

-(void)update:(CCTime)delta{



_coin.position=ccp(_coin.position.x - delta * scrollSpeed, _coinY);
if (CGRectIntersectsRect(_hero.boundingBox,_coin.boundingBox)) {
    _coinY=arc4random() % 801 + 100;

    _coin.position=ccp(_coin.position.x + 2000.f,_coinY);

}
else if(_hero.position.x >= _coin.position.x + 150){
    _coinY=arc4random() % 801 + 100;

    _coin.position=ccp(_coin.position.x + 2000.f,_coinY);
}

It works,but after that I found a small bug(I am not sure, whether it's related to this code) : sometimes, when hero touches coin, hero is like pushed away to the left. I have no idea why.

  1. How to fix it?
  2. Is that way, that I am using for coin ,right?

Solution

  • I see 2 issues with your approach:

    1. Hero bounces of the coin.

    To fix this you need to make your coin a sensor. This way you will still be notified about collisions, but the hero will simply pass through the coin without actually hitting it.

    I'm not sure if you can set this in SpriteBuilder, but probably you can enumerate all coins after loading the scene and set sensor property to YES:

    coin.physicsBody.sensor = YES;
    

    Things like this is one of the reasons I believe you first need to learn pure Cocos2D and only then use tools making your life easier such as SpriteBuilder. Which is a great tool, but in some cases you still need know what happens behind the scenes.

    2. You're mixing physics with things like CGRectIntersectsRect

    If you're using physics engine you need to detect collisions via collision delegate and not by checking CGRectIntersectsRect in update:.

    It is hard to explain how to do this in a few sentences, so here is a nice tutorial that shows how to detect collisions in Cocos2D v3 and of course there is a chapter about this in my book.

    By the way you shouldn't use update:at all when manipulating physics nodes, use fixedUpdate: instead.

    I hope this will help you to solve your issue.