Ball velocity problems solved!

The ball’s velocity has driven me nuts for days. I tried dragging the “bouncing” material to everywhere, modifying the rigidbody2D properties… It didn’t work. Sometimes the ball accelerated, sometimes the ball seemed to freeze.

I think today I have found where is the problem.

myRigidbody2D.velocity += velocityTweak;

The Rigidbody.velocity can increase or decrease without limits.

My solution (it is not an ideal solution!!):

myRigidbody2D.velocity += velocityTweak;
if (myRigidbody2D.velocity.magnitude < (0.9f * myVelocity)) 
            myRigidbody2D.velocity = myRigidbody2D.velocity * 1.1f;
else if (myRigidbody2D.velocity.magnitude > (1.1f * myVelocity)) 
            myRigidbody2D.velocity = myRigidbody2D.velocity * 0.9f;

In the Start():

myVelocity = Mathf.Sqrt(xVel * xVel + yVel * yVel);

Good solution!

I think it can be simplified to this:

myRigidbody2D.velocity += velocityTweak;
myRigidbody2D.velocity = myRigidbody2D.velocity.normalized * myVelocity;

That way the rigidbody will always have the velocity which you store in myVelocity.
Also keep in mind that calculating a vector’s magnitude is costly due to the expensive square root calculation it needs to do in the background.
If you use your approach with the two if-statements then you’ll probably want to store the magnitude in a temporary variable and use that instead of calculating the magnitude twice:

myRigidbody2D.velocity += velocityTweak;
float velMagnitude = myRigidbody2D.velocity.magnitude;

if (velMagnitude < (0.9f * myVelocity)) 
            myRigidbody2D.velocity = myRigidbody2D.velocity * 1.1f;
else if (velMagnitude > (1.1f * myVelocity)) 
            myRigidbody2D.velocity = myRigidbody2D.velocity * 0.9f;
1 Like

Yes, it’s a better solution! Thanks!!

THANK YOU! I was scouring the discussions trying to find a solution for this with no avail. I was about to create a new topic right before I saw this. Having the velocity vary too much just kills the game, especially when it goes to a turtle’s crawl or up to light speed!

Privacy & Terms