Moritz
Moritz

Reputation: 19

Calculate MaxVelocity after AddForce

I am making a game in which i have a few Balls moving on their own and never stopping. Now I tried to add a Forcefield which should redirect the balls, which I did with AddForce:

ball.gameObject.GetComponent<Rigidbody2D>().AddForce(ball.transform.forward * ((ball.speed/(70f+time)) * (ball.speed/(70f+time)))); 

(70 and time are just numbers to regulate the strength of the push).

But that speeded up the balls which is a huge problem. Which is why I tried to clamp the velocity:

ball.gameObject.GetComponent<Rigidbody2D>().velocity = Vector3.ClampMagnitude(ball.gameObject.GetComponent<Rigidbody2D>().velocity, ball.speed/75f); 

(Yes I will change the code so I dont have to get the Rigidbody 3 times.)

How would you calculate the Clamp, I have now via try and error figured out that ball.speed/75f works, but are there exact numbers? Has anyone an exact way to do it?

Upvotes: 0

Views: 37

Answers (1)

Pindwin
Pindwin

Reputation: 102

rigidbody.velocity is a vector - its direction defines direction of movement and its length defines speed of movement. Using these properties, you can:

  1. Save up the velocity length (float cachedLength = rigidbody.velocity.magnitude;).
  2. Apply the force you want to modify the direction
  3. Change velocity length to maintain the speed: rigidbody.velocity = rigidbody.velocity.normalized * cachedLength;

This way, you accept change in direction, but not in legth of the vector.

Edit. Just noticed you are using ball.speed in your question - never used Rigidbody2D, so naming can differ, but the mathematical principle is the same.

Upvotes: 0

Related Questions