开发者

"Realistic" collision in pong

开发者 https://www.devze.com 2023-01-15 10:39 出处:网络
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.

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开发者_JS百科 = 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.


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.


You should simply reverse the x or y value (change the sign) when colliding with a wall, window, etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消