- Home /
vertical and horizontal movement not working at the same time
i have some code to move a character one unit at a time: using System.Collections; using System.Collections.Generic; using UnityEngine; public class playerController : MonoBehaviour { private Vector2 newPosition; private bool movable; void Start() { movable = true; } void Update() { transform.position = newPosition; //horizontal movement if (Input.GetAxis("Horizontal") == 0) { movable = true; } if (Input.GetAxis("Horizontal") > 0) { if (movable == true) { newPosition.x += 1; movable = false; } } if (Input.GetAxis("Horizontal") < 0) { if (movable == true) { newPosition.x -= 1; movable = false; } } //vertical movement if (Input.GetAxis("Vertical") == 0) { movable = true; } if (Input.GetAxis("Vertical") > 0) { if (movable == true) { newPosition.y += 1; movable = false; } } if (Input.GetAxis("Vertical") < 0) { if (movable == true) { newPosition.y -= 1; movable = false; } } Debug.Log(transform.position); } }
when i use just the horizontal or just the vertical part of the code (delete the other part of the code), it moves one unit at a time (and i have to take my finger of the appropriate key between each one unit movement) as intended, but when i use the full code it moves a lot more without having to take my finger of the appropriate key. thanks
Answer by msaad2796 · Apr 10, 2021 at 05:34 PM
i have fixed it by moving the if (Input.GetAxis("Vertical") == 0) { movable = true;
into the if (Input.GetAxis("Horizontal") == 0) { movable = true;
like this: if (Input.GetAxis("Horizontal") == 0) { if (Input.GetAxis("Vertical") == 0) { movable = true; } }
Your answer
Follow this Question
Related Questions
how to move an object in 2D sense its position? 0 Answers
My controls are inverted when facing sideways. 1 Answer
2D Top-Down Movement: Transform.up and right don't change 2 Answers
How can I stop the player movement from being too fast while moving diagonally in my 2D game? 2 Answers
Prevent player from moving in a certain direction while moving in another 1 Answer