I have a code with some small error in it somewhere. It isn’t a compiler error but a logic error, so it fails to be shown in console. The code is for very basic movement.
The intent is when a key is pressed, the character moves in the corresponding direction (WASD). If an opposing direction is pressed while the other is still held down the character is meant to move the new direction.
using UnityEngine;
using System.Collections;
public class BasicMovement : MonoBehaviour {
private bool wDown = false;
private bool sDown = false;
private bool aDown = false;
private bool dDown = false;
public int speed;
private int relativeSpeed;
// Use this for initialization
void Start () {
relativeSpeed = speed;
}
// Update is called once per frame
void Update () {
GetKeyInput ();
if (wDown == true) {
transform.Translate (Vector3.forward * Time.deltaTime * relativeSpeed);
}
if (sDown == true) {
transform.Translate (Vector3.back * Time.deltaTime * relativeSpeed);
}
if (aDown == true) {
transform.Translate (Vector3.left * Time.deltaTime * relativeSpeed);
}
if (dDown == true) {
transform.Translate (Vector3.right * Time.deltaTime * relativeSpeed);
}
}
void GetKeyInput (){
if (Input.GetKeyDown (KeyCode.W)) {
Debug.Log("W");
wDown = true;
sDown = false;
}
if (Input.GetKeyDown (KeyCode.S)) {
Debug.Log("S");
sDown = true;
wDown = false;
}
if (Input.GetKeyDown (KeyCode.A)) {
Debug.Log("A");
aDown = true;
dDown = false;
}
if (Input.GetKeyDown (KeyCode.D)) {
Debug.Log("D");
dDown = true;
aDown = false;
}
if (Input.GetKeyUp (KeyCode.W)) {
wDown = false;
if (Input.GetKey (KeyCode.S)) {
sDown = true;
}
}
if (Input.GetKeyUp (KeyCode.S)) {
sDown = false;
if (Input.GetKey (KeyCode.W)) {
wDown = true;
}
}
if (Input.GetKeyUp (KeyCode.A)) {
aDown = false;
if (Input.GetKey (KeyCode.D)) {
dDown = true;
}
}
if (Input.GetKeyUp (KeyCode.D)) {
dDown = false;
if (Input.GetKey (KeyCode.A)) {
aDown = true;
}
}
}
}
The error is that when two keys (eg: W and D) are pressed pressing another key (S) changes nothing. However it only occurs with some key combinations, if D then A is pressed the character moves left as intended then both forward and left when W is added.
Basically, what is stopping my character from changing direction?
The Debug.Log’s show that in the example when W and D get pushed, and held down, when S is added it never gets pushed. There is no output saying S was pushed.