条件统一时如何停止变换位置?

我需要有人来帮助我处理Unity3d中的transform.position。我试图按M键时停止tranform.position。我尝试使用下面提到的代码,但它仍以相同的速度移动。

    if (Input.GetKeyDown(KeyCode.M))
    {
        transform.position += PlayerController.player.transform.forward * -0.00001f;
    }

    else
    {
        transform.position += PlayerController.player.transform.forward * -0.1f;
    }

在正常情况下,transform.position可以正常工作,但是当我按M键时,它的速度应该慢到现在看起来已经停止了。我认为其他条件运行良好。

评论
ncum
ncum
我试图按M键时停止transform.position。

Currently you reach your if block exctly in one single frame namely the moment the key goes down the first time. Input.GetKeyDown

在用户开始按下由key KeyCode枚举参数标识的关键帧期间,返回true。

For continues executions you would want to use Input.GetKey which

当用户按住key KeyCode枚举参数标识的键时,返回true。
if(Input.GetKey(KeyCode.M))
{
    // you will have to adjust the multiplicators
    transform.position += PlayerController.player.transform.forward * -0.00001f * Time.deltaTime;
}
else
{
    transform.position += PlayerController.player.transform.forward * -0.1f * Time.deltaTime;
}

Btw if you really want to stop the movement as you say you would probably rather simply use

if(!Input.GetKey(KeyCode.M))
{
    transform.position += PlayerController.player.transform.forward * -0.1f * Time.deltaTime;
}

and do nothing while M stays pressed

Note that your code is frame-rate dependent and you always should use * Time.deltaTime for converting your values from Units / frame into Units / second

点赞
评论
柯

You should use GetKey instead

Returns true while the user holds down the key identified by name. https://docs.unity3d.com/ScriptReference/Input.GetKey.html

You are using GetKeyDown that only returns true during the frame you pressed the key resulting in slowdown only one frame ¬

在用户开始按下键的帧期间返回true   按名称标识。

https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html

点赞
评论