3
votes

I have several balls in a world that collide with each other. There are static walls on all sides of the world.

Sometimes, they end up in a position where they keep on moving up/down or left/right along the same path (motion perpendicular to the wall?)

Is there any easy way to detect this, and then, apply a little rotation to it on either direction?

Pseudocode or code in any language that has box2d would be appreciated.

Edit: Image, as requested by @Andrew

enter image description here

If the ball keeps moving like this (left/right/left/right...), I want to give it a little push so it moves from the current path.

2
can you post an image with such situation please ? - Andrew
@Andrew Added an image. I hope it makes things clearer. - Dogbert
Do the balls collide with each other? - Raiden
@Raiden yes. That's how they end up in this "stuck" position. I want them to move across the whole screen uniformly. - Dogbert

2 Answers

1
votes

I think you can create your b2ContactListener subclass to detect ball-wall collisions (It is simple and explained in Box2D manual). After you made it store 3 velocity values for each of your balls.

  1. Before first ball-wall collision.
  2. After first ball-wall collision.
  3. After second ball-wall collision.

When you obtained these three velocities (use GetLinearVelocity function of b2Body) - check if they lie on the same line with some precision (have the same direction except the sign). If this condition is satisfied - apply a little rotation

0
votes

I thought you could measure the angle with each collision? I don't have time to post proper code now (tonight perhaps, if you need an example) but you could have some sort of mechanism that checks the angle of any collision between balls and walls.

If it's exactly 90 degrees, you flag the ball (either with userdata or in some external array), and start tracking the number of consecutive 90 degree collisions between walls and that ball. If two 90-degree collisions happen one after the other, you can safely assume the ball is stuck and give it a nudge.