简体   繁体   中英

Unity 2D Why does my character jump different heights every time?

So, my jumping is inconsistent, basically, every time i press space the character jumps different heihgts, even when standing still (not moving left, and right), why is that?

here is my code:

public bool onGround = false;
public float JumpHeight;
public Rigidbody2D gravidade;
// Start is called before the first frame update
void Start()
{
    
}



// Update is called once per frame
void Update()
{
    if (onGround == true)
    { 
        if (Input.GetKey(KeyCode.Space))
        {
            gravidade.AddForce(new Vector2(0, JumpHeight * Time.deltaTime), ForceMode2D.Impulse);
         
        }
    }
}
void OnCollisionEnter2D(Collision2D outro)
{
    if (outro.gameObject.CompareTag("ground"))
    {
        onGround = true;
    }
}
void OnCollisionExit2D(Collision2D outro)
{
    if (outro.gameObject.CompareTag("ground"))
    {
        onGround = false;

    }
}

You shouldn't multiply by delta time when applying a one-time force.

Time.deltaTime is the time completion time in seconds since the last frame. Check the documetation

This time is not constant. MonoBehaviour.FixedUpdate uses fixedDeltaTime instead of deltaTime, this fixedDeltaTime and the FixedUpdate is usually used for physics and it is quite an advanced topic.

Use a constant value instead of the Time.deltaTime to have always the same jump height.

It is different becuase it's calculated off of deltaTime, which is incosistent (time between two rendered frames if i'm not wrong), and it yields a slightly different value every time, which combined with multiplication has a bigger deviation from an average. Hope i helped to clarify this, cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM