- Home /
limit AddRelativeForce
I am using AddRelativeForce to move an object.
The problem is that when both Input.GetAxis ("Vertical") and Input.GetAxis ("Horizontal") are pressed, the object travels at the rate of 2.0 overall. I would like to limit the overall AddRelativeForce to 1, even if both directions are pressed. In other words, if both Input.GetAxis ("Vertical") and Input.GetAxis ("Horizontal") are pressed, then I want each of them to influence the object with a value of .5 so that the overall combined value is clamped at 1.0
var force = Input.GetAxis ("Vertical");
var torque = Input.GetAxis ("Horizontal");
rigidbody.AddRelativeForce (torque, 0, force);
Answer by duck · Apr 13, 2010 at 04:28 PM
This question is slightly confusing since you're using the term "Torque" (which relates to rotation) when you seem to be actually using it for linear force. However, ignoring that, it seems like what you want is to "normalize" the lengths of your horizontal and vertical forces so that the total "length" of the vector doesn't exceed 1.
This is not the same as making them add up to 1 - because if an object is moving at a speed of X:0.5 and y:0.5, it would actually be moving slower than an object that is moving at x:1, y:0. Normalizing the values as a vector will give you the results that I think you want (although please correct me if I have the wrong idea).
Since another version of AddRelativeForce accepts a Vector3 (as opposed to separate x,y,z values), you can make use of the normalization functions that unity has built into its Vector3 class:
var v = Input.GetAxis ("Vertical"); var h = Input.GetAxis ("Horizontal"); var relativeForce = Vector3(h, 0, v);
if (relativeForce.magnitude > 1) { relativeForce.Normalize(); }
rigidbody.AddRelativeForce(relativeForce);
Great Duck. Yes, even with my mishandled description you understood exactly what I was trying to do, thanks.
Is there any way to get a variable to normalize at a value other than 1?
Just out of curiosity, what would be the forward velocity of an object moving at X:0.5 and y:0.5?
"normalize at a value other than 1?" yes - normalize it to 1, then multiply by whatever value you want! :)
The velocity of something moving at x:0.5 y:0.5 would be about 0.707 - for more information, google pythagoras!
Your answer
Follow this Question
Related Questions
AddForce on GetAxis always sam direction? 1 Answer
Make a 2D Camera vertically stationary? 0 Answers
How do I make my character's speed stay consistent? 0 Answers
Rigid body rotation question 1 Answer