Need advice for some Phycis behavior

Below is my script. I want to make and Object jump with Physics, but only when it’s grounded. It works well except when 2 forces combine - the bounce of and the impulse I apply. Then the ball goes higher then it should. I wonder if there some smart trick to prevent that?

public class Movement : MonoBehaviour
{
    public float jumpForce;

    Rigidbody m_Rigidbody;
    Vector3 m_NewForce;
    bool isGrounded;

    void Start()
    {
        m_Rigidbody = GetComponent<Rigidbody>();
        m_NewForce = new Vector3(0.0f, 3.0f, 0.0f);
        isGrounded = false;
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        var v = Input.GetAxis("Vertical");

        if(v > 0f && isGrounded)
        {
            m_Rigidbody.AddForce(m_NewForce, ForceMode.Impulse);
        }
    }

    void OnCollisionEnter(Collision collision)
    {      
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }

    void OnCollisionExit(Collision collision)
    {
      
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = false;
        }
    }
}

try using ForceMode.VelocityChange

but if it absolutely fails, you can edit object’s velocity to implement jumping, for immediate reaction.
it’s a hack, but actually recommended by the docs, jumping is a physics hack anyway: you generate a force out of nothing.

you can take the existing velocity, and apply your jumping velocity, then cap it if it has a greater magnitude than plain jump.

var jumpVelocity = new Vector3(0f, 3f, 0f);

if(jumping occurs) {
  rb.velocity += jumpVelocity;
  if(rb.velocity.sqrMagnitude > jumpVelocity.sqrMagnitude) {
    rb.velocity = jumpVelocity.magnitude * rb.velocity.normalized;
  }
}
1 Like

Good idea, will try