views:

141

answers:

1

I want to write a pong in C# and XNA with friction and bounce. I tried to implement the collision as described by Garet Rees in a previous question.

Here is the basic algorithm I use for pong:

  1. Seperate the colliding objects so that they are no longer colliding.
  2. Get the surface normal for collision response.
  3. Compute the new velocity - here is my problem.

Here is the code I am currently using for collision response:

Vector2 normalizedVelocity = Velocity;
normalizedVelocity.Normalize();

Vector2 u = -Velocity * Vector2.Dot(normalizedVelocity, normal);
Vector2 w = Velocity - u;

Velocity = w - u;

For testing purposes I assume no friction and perfect elasticity. This piece of code works fine for a object just moving in one direction, e.g.:

Velocity.X = 100;
Velocity.Y = 0;

or

Velocity.X = 0;
Velocity.Y = 100;

But when I test with a diagonal moving ball, e.g.:

Velocity.X = 100;
Velocity.Y = 40;

The resulting velocity is not what I am assuming it should be.

+4  A: 

I think you want to do

Velocity = Velocity + 2 * normal * Vector2.Dot(Velocity, normal);

(where normal is the normalized surface normal pointing out of the surface the ball collides with)

Rather than

Vector2 u = -Velocity * Vector2.Dot(normalizedVelocity, normal);
Vector2 w = Velocity - u;

Velocity = w - u;

since velocity * Vector2.Dot(...) has the same heading as velocity, but balls generally change direction when bouncing ...

If you also want friction, you'll have to model the spin of the ball, and the formulae get a bit more complex.

meriton