I’ve got a basic character controller that can move up (backwards), down (forwards), left and right using WASD. However, I think because of the order of my GetKey statements, if I hold S after W or D after A, the character will start moving down while already moving up, or right while already moving left- however, if I hold W after S or A after D, the opposite won’t occur. It’s a little detail but it is annoying me, so I was wondering if there was any way to stop it? Strangely enough, as shown in the video console logs, the code acknowledges that A is being held, it just won’t turn the character and make it move.
For more info, I don’t want the movement to stop if I press two keys, I just want the character to keep moving in the direction of whichever key was pressed last, like what happens when S is pressed after W or D after A. (The other forums I looked at all wanted the character to stop, so people just offered entirely alternate code, hence why I’m asking my own question)
using UnityEngine;
using static UnityEngine.GraphicsBuffer;
public class player : MonoBehaviour
{
[SerializeField] private float moveSpeed = 4f;
Quaternion leftAngle = Quaternion.Euler(0, -180, 0);
Quaternion rightAngle = Quaternion.Euler(0, 0, 0);
[SerializeField] private bool flipped = false;
[SerializeField] private float turnSpeed = 12f;
private void Update() {
Vector2 inputVector = new Vector2(0, 0);
if (Input.GetKey(KeyCode.W)) {
inputVector.y = +1;
Debug.Log("Pressing W");
}
if (Input.GetKey(KeyCode.S)) {
inputVector.y = -1;
Debug.Log("Pressing S");
}
if (Input.GetKey(KeyCode.A)) {
inputVector.x = -1;
Debug.Log("Pressing A");
}
if (Input.GetKey(KeyCode.D)) {
inputVector.x = +1;
Debug.Log("Pressing D");
}
inputVector = inputVector.normalized;
Vector3 moveDirection = new Vector3(inputVector.x, 0f, inputVector.y);
transform.position += moveDirection * moveSpeed * Time.deltaTime;
if (!flipped && inputVector.x < 0) {
flipped = true;
}
if (flipped && inputVector.x > 0) {
flipped = false;
}
if (flipped) transform.rotation = Quaternion.Lerp(transform.rotation, leftAngle, turnSpeed * Time.deltaTime);
if (!flipped) transform.rotation = Quaternion.Lerp(transform.rotation, rightAngle, turnSpeed * Time.deltaTime);
}
}