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;
}
}