My character in my game moves in a diagonal direction, and I do not want it to. I want it to move up left down and right, based off of the last key that was pressed, but I’m not sure quite sure how to set this up:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
Rigidbody2D rbody;
Animator anim;
public float speed;
// Use this for initialization
void Start () {
rbody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void FixedUpdate () {
Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (movement_vector != Vector2.zero)
{
anim.SetBool("iswalking", true);
anim.SetFloat("input_x", movement_vector.x);
anim.SetFloat("input_y", movement_vector.y);
}
else
{
anim.SetBool("iswalking", false);
}
speed = 1.6f;
rbody.MovePosition(rbody.position + movement_vector * Time.deltaTime * speed);
}
}
You can check to see if both x and y values are non-zero in your movement vector. If that’s the case, it will move diagonally. If both aren’t 0, set one to 0 to turn it into a non-diagonal move. Or simply block the move entirely. However you want to handle it in that case.