简体   繁体   English

如何检查空格键是否被按下一次? 统一 3d c#

[英]how to check if the space key is pressed once? unity 3d c#

I'm trying to make a plane controller by following a tutorial but I want it to check if the space key is pressed once, then run the if statement forever.我正在尝试按照教程制作飞机 controller 但我希望它检查是否按下了一次空格键,然后永远运行 if 语句。 I'm kinda new to unity and c# so if u want to, please explain your answer, thanks: :D我对统一和 c# 有点陌生,所以如果你想,请解释你的答案,谢谢::D

here is my plane controller script:这是我的飞机 controller 脚本:

using UnityEngine;

public class PlayerMovement1 : MonoBehaviour
{

public bool throttle => Input.GetKey(KeyCode.Space);

public float pitchPower, rollPower, yawPower, enginePower;

private float activeRoll, activePitch, activeYaw;

private void Update()
{
    if (throttle)
    {
        transform.position += transform.forward * enginePower * Time.deltaTime;

        activePitch = Input.GetAxisRaw("Vertical") * pitchPower * Time.deltaTime;
        activeRoll = Input.GetAxisRaw("Horizontal") * rollPower * Time.deltaTime;
        activeYaw = Input.GetAxisRaw("Yaw") * yawPower * Time.deltaTime;

        transform.Rotate(activePitch * pitchPower * Time.deltaTime,
            activeYaw * yawPower * Time.deltaTime,
            -activeRoll * rollPower * Time.deltaTime,
            Space.Self); 
    }
    else
    {
        activePitch = Input.GetAxisRaw("Vertical") * (pitchPower / 2) * Time.deltaTime;
        activeRoll = Input.GetAxisRaw("Horizontal") * (rollPower / 2) * Time.deltaTime;
        activeYaw = Input.GetAxisRaw("Yaw") * (yawPower / 2) * Time.deltaTime;

        transform.Rotate(activePitch * pitchPower * Time.deltaTime,
            activeYaw * yawPower * Time.deltaTime,
            -activeRoll * rollPower * Time.deltaTime,
            Space.Self);
    }
}
}

thanks again for taking time and reading this!再次感谢您花时间阅读本文!

Sounds like you want to have a switch instead of a continous press like eg听起来你想要一个开关而不是连续按下,例如

// Store the actual value in a field
private bool _throttle;

// Too keep the public read-only access
public bool throttle => _throttle;

private void Update ()
{
    // Instead of checking for a continous press
    // this is only true in the one frame the key goes down
    // and simply inverts the value of _throttle
    if(Input.GetKeyDown(KeyCode.Space)) _throttle = !_throttle;

    ...
}

I think your issue here is that the throttle bool is assigned only once when the script is initialized.我认为您的问题是在脚本初始化时仅分配一次油门布尔值。 If you want to keep it similar you could turn it into a property instead.如果你想让它保持相似,你可以把它变成一个属性。

public bool throttle
{
    get { return Input.GetKey(KeyCode.Space); }
}

If you plan on calling throttle in a bunch of place though I'd suggest to simply: throttle = Input.GetKey(KeyCode.Space);如果您打算在一堆地方调用节流阀,但我建议简单地说:throttle = Input.GetKey(KeyCode.Space); at the beginning of the update loop.在更新循环的开始。

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

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