- Home /
(2D Movement) How do I make my sprite move up, down, left, and right, without moving diagonal?
I want to make my sprite move up, down, left, and right, but never diagonal. Also, I wanted to make it with translate, and not with a rigid body. So far, this is the code I have. using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Tank : MonoBehaviour { [SerializeField] float moveSpeed = 5f; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { Move(); SpriteRotate(); } private void Move() { Vector3 movement= new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0f); transform.position += movement * moveSpeed * Time.deltaTime; } private void SpriteRotate() { if (Input.GetKeyDown(KeyCode.W)) { transform.eulerAngles = new Vector3(0, 0, 0); } else if (Input.GetKeyDown(KeyCode.S)) { transform.eulerAngles = new Vector3(0, 0, 180); } else if (Input.GetKeyDown(KeyCode.A)) { transform.eulerAngles = new Vector3(0, 0, 90); } else if (Input.GetKeyDown(KeyCode.D)) { transform.eulerAngles = new Vector3(0, 0, -90); } } }
Answer by SirPaddow · Aug 29, 2019 at 11:41 AM
Well, you can't prevent the player from pressing two keys at the same time, so first you need to decide how your game will handle such a case. For instance, you could decide that if there is a vertical and horizontal input at the same time, the vertical movement is prioritized, something like this:
private void Move() {
Vector2 movement = Vector2.zero;
if (Input.GetAxis("Vertical") != 0)
movement = new Vector2(0, Input.GetAxis("Vertical"));
else if (Input.GetAxis("Horizontal" != 0)
movement = new Vector2(Input.GetAxis("Horizontal"), 0);
transform.position.Translate(movement * moveSpeed * Time.deltaTime);
}
You don't need a rigidbody to do this, since you directly manipulate the transform position. Using transform.position += [...] or transform.Translate([...]) have the same result.
Your answer
Follow this Question
Related Questions
2D Directional top down movement,Topdown 2d Directional Movement 0 Answers
2D Topdown movement without sliding 2 Answers
How do I make a 2D object face the direction it is moving in top down space shooter 1 Answer
Top down 2d movement without being affected by rotation 2 Answers
2D Top Down Character Controller 1 Answer