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. I'm kinda new to unity and c# so if u want to, please explain your answer, thanks: :D
here is my plane controller script:
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); at the beginning of the update loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.