tags:

views:

28

answers:

2

I currently have a method that checks to see if I go out of bounds either from either the top/bottom/sides. The object itself is a ball, and I have a question about getting the ball bouncing off the edges correctly? How do I go about this?

// The behavior is not quite what I want.

if ( InsideOfBounds )
{
     Vector3 mCenter = Ball.getCenter();
     Vector3 normalizeV = tempCenter;
     normalizeV.Normalize();
     mHeroBall.setVelocity(-testSpeed * normalizeV);
}
+1  A: 

I can provide you with an example from a Breakout-clone written in XNA:

Ball.cs

Basically, you flip the right component of velocity to make a 'perfect' rebound. If you want, you can add friction or elasticity by multiplying by a coefficient like 0.95 or 1.1 so your ball speed change.

jv42
A: 

When you update the position of your object (ball), you want to check if the new value is out of bounds (and which bount Top\Bottom or Left\Right). If the it actually out of bounds, flip the correct element in your speed vector.

example: if the ball has passed the left bound then BallSpeed.X = -BallSpeed.X

don't forget to update the ball's position with the new speed and not the old at this point, or it will fly off the screen for the current frame (unless that isn't an issue).

Neowizard