Detecting a hit and responding

I have an object in my game which I want to move in a certain direction with a constant velocity. (This one I successfully implemented)

Thins is when the Object hits the screen boundaries i want to reverse its velocity.
I defined a world body for the screen boundaries with the static type
I defined a world body for the object with the dynamic type
I detect the collision using a contact listener. Thing is when I detect the collision and reverse the body's velocity the collision is still detected in the contact listener and the velocity is changed again (although it should return back from the screen to the other end!)

What am I doing wrong here ?

Thanks
If you have a body coming into contact with another, you do not need to handle the movement, that's the one of the main reasons for having a physics engine - it does it for you. Unless you want to do other things upon the collision, you don't even need to detect it with a contact listener.

Your body should automatically bounce off the boundary assuming it is correctly set up to do so. Check that you have some restitution, mass etc.
Also in certain situations you may need to change a figure in the box2d code if you get bodies sticking each other.
I have the same scenario as mkfield posted. I have bodies that automatically move along the ground. In other words, I am continually applying a force (using the ApplyForce method) to keep them moving. However, I need the bodies to reverse direction when they run into a wall.

The problem is that collisions are constantly generated between the body and the ground terrain so I don't if the body has hit an obstacle (wall, world boundary, etc.) or not. If I can tell when it hits some impassable terrain, I can start applying the force in the opposite direction.

One way I might try to solve this is to check if the position of the body has not changed for a certain amount of time and reverse direction in that case. (Of course, I have to account for the case where the body has stopped to attack an enemy body, in which case the body should NOT turn and run away.) 🙂

Anyone know the preferred way to handle this kind of situation with Box2d?

Thanks,
Joe
For that, usually you would use BeginContact and check the two fixtures that just collided. You could either compare fixture pointers directly, or compare some user data that you set in the fixtures. From each fixture you can also obtain the body it belongs to, so you could do a similar check on those if it was more logical (either compare the body pointer directly or the user data you set in it).
Thanks! I was already using BeginContact but I hadn't thought of comparing the fixtures themselves. I ended up saving the left and right walls of the world boundary as member variables and comparing those to the contact fixture. Works great!

Original thread: https://box2d.org/forum/viewtopic.php?t=7125