Search code examples
box2dcocos2d-x

Cocos2d Box2d collision look ahead


So I am trying to test collision in cocos2d-x with box2d. In my game loop I am moving the sprite and not using box2d physics. I do have it setup with a body in box2d so that I can have the rectangles right, however when it collides it is over lapping with the other object. I want it to stop where it collided at. I know why it is doing it (which is because it is told to move 8 points and the collision happens at 4) but I am not sure how to get it to stop exactly where it collides. If I do this:

float x = a->getPosition().x + (a->getContentSize().width / 2) + (b->getContentSize().width / 2);
b->setPositionX(x);

It works but you can see it jump after it is done moving the 8 points and back 4 points. I am not sure if I am doing this completely wrong or what but I cant seem to get it to stop where it collided without jumping. Also just so you know what the update looks like:

Vec2 pos = _enemy->getPosition();
pos.x -= _scrollSpeed;
_enemy->setPosition(pos);

_scrollSpeed = 8 btw

Any help is greatly appreciated.


Solution

  • You could create a field in your class which tells whether object is moving or not and set to true/false in Begincontact. Then in update() method just check whether this field is set then you will know if you should move it or not.

    Edit: Remember to check this before world->step() is called