簡體   English   中英

如何檢查空格鍵是否被按下一次? 統一 3d c#

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

我正在嘗試按照教程制作飛機 controller 但我希望它檢查是否按下了一次空格鍵,然后永遠運行 if 語句。 我對統一和 c# 有點陌生,所以如果你想,請解釋你的答案,謝謝::D

這是我的飛機 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);
    }
}
}

再次感謝您花時間閱讀本文!

聽起來你想要一個開關而不是連續按下,例如

// 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;

    ...
}

我認為您的問題是在腳本初始化時僅分配一次油門布爾值。 如果你想讓它保持相似,你可以把它變成一個屬性。

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

如果您打算在一堆地方調用節流閥,但我建議簡單地說:throttle = Input.GetKey(KeyCode.Space); 在更新循環的開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM