Disable diagonal following of player

Viewed 25

So I have a script for my player where I have disabled diagonal move. I then created a script for his dog companion that follows him in the world and it's almost perfected except when I do a direction change from left/right to up/down or vice versa the dog will follow at a diagonal and looks really weird since there is no animations and he basically slides there. I tried to disable diagonal like how I did for the player but it doesn't work. Is there a way to go about this or would it be better to just add in a diagonal animation for just the dog?

public class Bowser : MonoBehaviour
{
    public float speed;
    private Transform target;
    private Vector2 move;
    private Animator anim;

    private void Awake()
    {
        anim = GetComponent<Animator>();

    }
    // Start is called before the first frame update
    void Start()
    {
        target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
    }

    // Update is called once per frame
    void Update()
    {
        move.x = Input.GetAxisRaw("Horizontal");
        move.y = Input.GetAxisRaw("Vertical");
        if (Vector2.Distance(transform.position, target.position) > 1.5)
        {
            // Code attempt to get rid of diagonal movement
            if (move.x != 0) move.y = 0;

            if (move != Vector2.zero)
            {
                anim.SetFloat("moveX", move.x);
                anim.SetFloat("moveY", move.y);
                anim.SetBool("moving", true);
            }
            transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
        }
        else
            anim.SetBool("moving", false);
    }
}
3 Answers

Instead of just checking for 0 you could just use the bigger value

if (Mathf.Abs(move.x) > (Mathf.Abs(move.y)) move.y = 0;
else move.x = 0;

it would be better if you just provided diagonal animations for the dog

Thanks for the advice in the end I found that it became a smoother transition to just add this


        if (Mathf.Abs(move.x) > .01f)
            targetPosition.y = transform.position.y;
        if (Mathf.Abs(move.y) > .01f)
            targetPosition.x = transform.position.x;

and then change all my target.Position to the targetPosition

Related