GetKey?

This code is supposed to add a force to the player when the W key is pressed.
Here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovementControl : MonoBehaviour {

    bool ForwardDown = Input.GetKeyDown(KeyCode.W);
    bool ForwardUp = Input.GetKeyUp(KeyCode.W);
    bool isForward;

    public Rigidbody physics;

    // Use this for initialization
    void Start () {
        physics = GetComponent<Rigidbody>();
    }
   
    // Update is called once per frame
    void Update () {
        if (ForwardDown)
            isForward = true;
        if (ForwardUp)
            isForward = false;
        if(isForward) {
            physics.AddForce (transform.forward * 10);
        }
    }
}

The thing about GetKeyDown and GetKeyUp is that it only activates for 1 frame
If you use GetKey, it will always return true while being pressed.

if (Input.GetKey(KeyCode.W)
physics.AddForce(transform.forward * 10);

You don’t need to event-drive-check it like that, and in any case you’re only calling the Input functions once, at variable instantiation.

Instead, this will work, entirely inside of your Update() loop:

 bool GoForward = Input.GetKey(KeyCode.W);
 if (GoForward) {
    //  do your go forward stuff
 } else {
    // do your I'm not going forward stuff (might be nothing?)
 }

A bit simpler that way… no external stuff needed.

Edit: yeah, exactly what @Vedrit said, but I like having that extra variable around to debug it when it misbehaves, and to give you a point to shim in other things like maybe a touchscreen input!

Wow that was fast! Thank you!

1 Like