简体   繁体   English

Unity 2D 为什么我的角色每次跳的高度都不一样?

[英]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. Time.deltaTime是自上一帧以来的时间完成时间(以秒为单位)。 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. MonoBehaviour.FixedUpdate 使用的是 fixedDeltaTime 而不是 deltaTime,这个 fixedDeltaTime 和FixedUpdate通常用于物理,是一个相当高级的话题。

Use a constant value instead of the Time.deltaTime to have always the same jump height.使用常量值而不是Time.deltaTime以始终具有相同的跳跃高度。

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.它是不同的,因为它是根据 deltaTime 计算的,它是不一致的(如果我没记错的话,两个渲染帧之间的时间),并且每次都会产生略有不同的值,与乘法相结合与平均值的偏差更大。 Hope i helped to clarify this, cheers!希望我能帮助澄清这一点,干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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