Explaining Incorrect Code on GetKey

Hello, i have been trying to code simple character movement and through trial and error i figured it out. But why did my initial code not work? My initial code was just using bool Right and Bool Left to move, but the If statements would not seem to function. So i decided to just place Getkey into the If statement parameters (which worked). So far, right movement would work, but left movement would not. I decided to leave the Left in the If statement parameter in the example below so i can show you what i initially had in mind. Thanks!

using UnityEngine;
using System.Collections;

public class Movement : MonoBehaviour {

    public int MovementSpeed;

    bool Right = Input.GetKeyDown(KeyCode.D);
    bool Left = Input.GetKeyDown(KeyCode.A);


    // Use this for initialization
    void Start ()
    {
	
	}

    // Update is called once per frame
    void Update()
    {

        if (Input.GetKey(KeyCode.D))

        {
            // This Translates Right
            transform.Translate(MovementSpeed * Time.deltaTime, 0, 0);
        };


        if (Left)
        {
            // This Translates Left
            transform.Translate(-MovementSpeed * Time.deltaTime, 0, 0);

        };



    }
}

1 Answer

1

In above code, values for bool variables RIght and Left are set once only during declaration. At that time the keys are likely not being pressed, the values are defined as false and never get updated.

Input.GetKeyDown() function should be called from within Update() as the value gets reset each frame. Refer to the unity reference here: https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html

Alternatively, try using the Input.GetAxis() function instead where the horizontal movement is already mapped to the a and d keys. See Unity manual https://docs.unity3d.com/Manual/ConventionalGameInput.html