I’m very new to Unity and am trying to set up 8 directional movement and animation for my Sprite. At present, 4 directional movement (up, down, left, right) is working fine, but diagonal movement is not working for all but one direction. This is what happens:
Press Right + Down: Right walking animation (correct)
Press Right + Up: Up walking animation (incorrect, I want Right Walking animation)
Press Left + Down: Down walking animation (incorrect, I want Left Walking animation)
Press Left + Up: Up walking animation (incorrect, I want Left Walking animation)
In summary, if travelling horizontally I want to favour the horizontal/x axis animation.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed;
public Animator animator;
//get input from player
//apply movement to sprite
private void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, vertical);
AnimateMovement(direction);
transform.position += direction * speed * Time.deltaTime;
}
void AnimateMovement(Vector3 direction)
{
if (animator != null)
{
if(direction.magnitude > 0)
{
animator.SetBool("isMoving", true);
animator.SetFloat("horizontal", direction.x);
animator.SetFloat("vertical", direction.y);
}
else
{
animator.SetBool("isMoving", false);
}
}
}
}
4