- Home /
The question is answered, right answer was accepted
Disable diagonal movement in unity 2D
Hi all, I am in the proces of creating a little RPG styled game, and in that proces I have created a player movement script. The script itself is working fine, however, when I am holding down two keys (for instance 'W' and 'D'), or is using a joystick, the player object can move diagonally. How can I avoid that from happening?
The player may only go in one of four directions (up, down, left or right), and may not move diagonally. I am using the Input.GetAxisRaw() method atm.
using UnityEngine;
using System.Collections;
public class PlayerMovementScript : MonoBehaviour {
public float movementSpeed = 1.5f;
private Animator animator;
// Use this for initialization
void Start () {
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
float xPos = Input.GetAxisRaw("Horizontal");
float yPos = Input.GetAxisRaw("Vertical");
bool isWalking = (Mathf.Abs(xPos) + Mathf.Abs(yPos)) > 0;
animator.SetBool("isWalking", isWalking);
if (isWalking) {
animator.SetFloat("x", xPos);
animator.SetFloat("y", yPos);
}
transform.position += new Vector3(xPos, yPos, 0).normalized * Time.deltaTime * movementSpeed;
}
}
Answer by lordlycastle · Apr 20, 2015 at 04:12 PM
It depends on how you want to respond when two keys are pressed? Do you wanna move to last direction pressed, or keep going in the direction you were. You simply need to do check and only assign either x or y values to the input. The following will do the latter of the two scenarios.
bool mvHoz;
bool mvVer;
float xPos = 0, yPos = 0;
if (Input.GetAxis(“Vertical”) != 0 && Input.GetAxis(“Horizontal”) != 0){
if (mvHoz){
yPos = Input.GetAxis(“Vertical”);
}else if (mvVer){
xPos = Input.GetAxis(“Horizontal”);
}
}else {
mvHoz = Input.GetAxis(“Horizontal”) != 0;
xPos = Input.GetAxis(“Horizontal”);
mvVer = Input.GetAxis(“Vertical”) != 0;
yPos = Input.GetAxis(“Vertical”);
}
transform.position += new Vector3(xPos, yPos, 0).normalized * spd * Time.deltaTime;
I couln't get your example to work, unless I changed the GetAxis() method to be GetAxisRaw(), so it's good now, thank you!
Could you please explain what would be your method for moving to last direction pressed ?
Follow this Question
Related Questions
Cannot dash in left-down, left-up and right-down directions? 2 Answers
Character Not Moving RPG Game 0 Answers
Circular movement of the player 0 Answers
Help!How to validate the client position in headless unity? 0 Answers
Player movement for iOS? 1 Answer