0
\$\begingroup\$

I've started testing movement using the example code in this answer of making a body accelerate to a target velocity

    private void FixedUpdate()
    {
        Vector2 input = GetInput();

        if (Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon)
        {
            Vector3 desiredVelocity = new Vector3(input.x * speed, 0f, input.y * speed);            

            Vector3 delta = desiredVelocity - body.velocity;
            Vector3 acceleration = delta / Time.deltaTime;
        
            if (acceleration.sqrMagnitude > maxAccel * maxAccel)
            {
                acceleration = acceleration.normalized * maxAccel;
            }            

            body.AddForce(acceleration, ForceMode.Acceleration);
        }
    }

and I've encountered the following curious behavior: https://imgur.com/snGyVYK When moving the body by applying force, the body seems to levitate as if gravity is not being applied. It actually is being applied but it seems as if the force being applied to the body is overriding the force of gravity because as soon as I let go of the movement keys the body suddenly drops. I am not applying any force on the y axis so I'm not sure what exactly is at play here. What is going on here and what can I do to mitigate this behavior?

\$\endgroup\$
2
\$\begingroup\$

You're not applying just a horizontal force. You're applying a vertical force too.

Your desiredVelocity is constructed with a y component of zero, saying "I desire that this object should hover instead of falling," and the rest of the code then tries to honour this stated desire.

To fix that, just set delta.y = 0 before you calculate your acceleration, to say "I don't care about movement on the vertical axis — leave that unaffected by this input acceleration"

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.