简体   繁体   English

强制玩家在一定时间之前进入GetKeyUp

[英]Force player to GetKeyUp before a certain amount of time

So I am working on this 2D runner and I am using the transform.position function, but I have noticed that this makes gravity in Unity not work. 因此,我正在研究此2D运行器,并且正在使用transform.position函数,但是我注意到这使Unity中的重力无法工作。 I still want it to work so I have set up this artificial gravity (see in script) however if you hold the W button down the person can keep flying forever. 我仍然希望它能正常工作,所以我已经设置了这个人造重力(请参见脚本),但是如果按住W键,该人可以永远飞行。 I only want the person to be able to be in the air for a second. 我只希望这个人能够在空中停留一秒钟。 How do I do this? 我该怎么做呢?

if(Input.GetKeyDown(KeyCode.W) && transform.position.y < 0.1)
{
    target_position = new Vector2(transform.position.x, transform.position.y + jump_force);
}

//gravity
if (Input.GetKeyUp(KeyCode.W))
{
    target_position = new Vector2(transform.position.x, transform.position.y - jump_force);
}

So I figured it out. 所以我想通了。

 if(Input.GetKeyDown(KeyCode.W) && transform.position.x > max_left && transform.position.x < max_right && transform.position.y < 0.1)
    {
        target_position = new Vector2(transform.position.x, transform.position.y + jump_force);
        Invoke("normal_position", jump_timer);

    }

}

public void normal_position()
{
    target_position = new Vector2(transform.position.x, 0);
}

The jump timer is jut how long you want it to take until the object returns to the ground. 跳跃计时器是判断您要花费多长时间直到物体返回地面。

You're not actually implementing any gravity, because you're waiting for a KeyUp event. 您实际上并没有实现任何重力,因为您正在等待KeyUp事件。 Don't wait. 不要等 Just do. 做就是了。

if (Input.GetKeyDown(KeyCode.W))
{
    // Do your movement stuff
}

// Just implement gravity here
transform.position = transform.position - Vector3.Down;

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

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