So i have the following code to make a rigidbody move:
void Update()
{
inputVector.x = Input.GetAxis("Horizontal") * acceleration * rigidbody.mass * Time.deltaTime;
inputVector.y = Input.GetAxis("Vertical") * acceleration * rigidbody.mass * Time.deltaTime;
rigidbody.AddRelativeForce(inputVector.x, 0, inputVector.y);
horizontalMovement = new Vector2(rigidbody.velocity.x, rigidbody.velocity.z);
if (horizontalMovement.magnitude > currentMaxSpeed)
{
horizontalMovement.Normalize();
rigidbody.velocity = new Vector3(horizontalMovement.x * currentMaxSpeed, rigidbody.velocity.y, horizontalMovement.y * currentMaxSpeed);
}
}
The problem is, that Applyforce doesn’t seem to care that i resett the velocity of the body if it’s going too fast, which would happen if i set acceleration too high. So i wonder, when is it actually applied ?
And more importantly, how do i fix that ? I tried setting the velocity manually, which indeed solved the problem (hence this question). But, well i can’t seem to figure out how i would go about and add my cute little inputVector to the velocity. That’s because my brain has trouble following this whole relative rotation thingy. Meaning that i don’t know how i would convert that worldspace-input to relative-input.
Also: Have patient with me, i’m really bad at math and come from xna, which uses a slightly different coordinatesystem. And i also only did 2D so far, where relative rotation is relatively irrelevant =) (And you also have to write pretty much all physics stuff yourself, so you at least know what’s going on :/)
Edit: I actually figured it out.
inputVector = rigidbody.transform.forward * Input.GetAxis("Vertical");
inputVector += rigidbody.transform.right * Input.GetAxis("Horizontal");
inputVector.Normalize();
inputVector = inputVector * acceleration * rigidbody.mass * Time.deltaTime;
rigidbody.velocity += new Vector3(inputVector.x, 0, inputVector.z);
horizontalMovement = new Vector2(rigidbody.velocity.x, rigidbody.velocity.z);
if (horizontalMovement.magnitude > currentMaxSpeed)
{
horizontalMovement.Normalize();
rigidbody.velocity = new Vector3(horizontalMovement.x * currentMaxSpeed, rigidbody.velocity.y, horizontalMovement.y * currentMaxSpeed);
}
Still, the question remains. What’s up with AddForce ? I’d also welcome any comments on the code. Sigh… and all that just because i want the code to correct for wrong input