开发者

C# XNA Making the object stay within the bounds

开发者 https://www.devze.com 2023-01-20 19:03 出处:网络
I currently have a method that checks to see if I go out of bounds either from either开发者_如何学Python the top/bottom/sides. The object itself is a ball, and I have a question about getting the ball

I currently have a method that checks to see if I go out of bounds either from either开发者_如何学Python 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);
}


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.


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).

0

精彩评论

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