-1

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?

2
  • If you want to change direction without adding speed .. why not just change the velocity directly? Commented Jan 23 at 13:40
  • 1. I'm not sure what you really want to do, please clarify your question. 2. Why is speeding up the ball a huge problem? 3. What is ball.speed and what is its relationship with velocity? Commented Jan 23 at 14:53

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ball.speed has nothing to do with Rigidbody(2D)
Sure, I don't know Rigidbody2D API, assumed just as much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.