如何检查空格键是否按过一次?统一3d c#
我试图按照教程制作一个平面控制器,但我希望它检查空格键是否按下一次,然后永远运行if语句。我对unity和c有点陌生,所以如果你想,请解释你的答案,谢谢D 这是我的平面控制器脚本:如何检查空格键是否按过一次?统一3d c#,c#,unity3d,C#,Unity3d,我试图按照教程制作一个平面控制器,但我希望它检查空格键是否按下一次,然后永远运行if语句。我对unity和c有点陌生,所以如果你想,请解释你的答案,谢谢D 这是我的平面控制器脚本: using UnityEngine; public class PlayerMovement1 : MonoBehaviour { public bool throttle => Input.GetKey(KeyCode.Space); public float pitchPower, rollPower
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);
}
}
}
再次感谢您抽出时间阅读本文 我认为您这里的问题是,在脚本初始化时,throttle bool只分配一次。如果你想保持它的相似性,你可以把它变成一个财产
public bool throttle
{
get { return Input.GetKey(KeyCode.Space); }
}
如果您计划在一堆地方调用throttle,我建议您只需:throttle=Input.GetKey(KeyCode.Space);在更新循环的开始处。听起来像是你想要一个开关,而不是像这样的连续按下
// 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;
...
}
我的意思是如果你按空格一次,if语句将永远运行。如果你再按一次,它就会停止
public bool throttle=>Input.GetKey(KeyCode.Space)
与public bool throttle{get{return Input.GetKey(KeyCode.Space);}}
或public bool throttle{get=>Input.GetKey(KeyCode.Space);}
。。这些只是不同的书写方式;)非常感谢您的回复!但是你能解释一下你的答案吗?@KingPerfet_uu我补充了一些评论?有任何疑问或问题吗?没有,一点也不谢谢你抽出时间:)