Keith Power
Keith Power

Reputation: 14141

Unity get X & Y of movment

I have a top down unity project. The player moves to where the screen is tapped.

I would like now to have the correct animation play for the direction the player is moving. I have set up the Blend Tree which works fines and I have the float parameters of Horizontal, Vertical and Magnitude.

However when I tapped the screen the player animation does not change direction or if it does it points in the wrong direction half way through the movement. I am sure it is the X Y values I am using but I am not sure how to get the correct.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    float speed = 2f;
    Vector2 targetPos;

    private Rigidbody2D myRigidbody;
    private Animator myAnim;

    private void Start()
    {
        myRigidbody = GetComponent<Rigidbody2D>();
        myAnim = GetComponent<Animator>();
        targetPos = transform.position;
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            targetPos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
        }
        if ((Vector2)transform.position != targetPos)
        {
            Move();
        }
    }

    void Move()
    {
        transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);

        myAnim.SetFloat("Horizontal", transform.position.x);
        myAnim.SetFloat("Vertical", transform.position.y);
        myAnim.SetFloat("Magnitude", transform.position.magnitude);
    }
}

Upvotes: 0

Views: 520

Answers (1)

Ruzihm
Ruzihm

Reputation: 20259

You need to set the floats according to the direction moved, not the new position of the transform. To do this, you need to find the difference between the new position and the old position, and use that vector instead.

Also, since you're handing magnitude separately, you may want to normalize the movement vector for the components. That depends on how your blends are set up.

However, if your movement takes you to the target position, you'll want to set the magnitude to zero, instead.

void Move()
{
    Vector2 oldPos = transform.position;
    transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);

    Vector2 movement = transform.position - oldPos;

    if (transform.position == targetPos) 
    {
        myAnim.SetFloat("Magnitude", 0f);
    } 
    else 
    {
        myAnim.SetFloat("Magnitude", movement.magnitude);
    }

    # You may need to normalize for your components.
    # Vector2 movementNormed = movement.normalized;
    # myAnim.SetFloat("Horizontal", movementNormed.x);
    # myAnim.SetFloat("Vertical", movementNormed.y);

    # Otherwise, just use the ordinary components.
    myAnim.SetFloat("Horizontal", movement.x);
    myAnim.SetFloat("Vertical", movement.y);

}

Upvotes: 1

Related Questions