- Home /
[C#] Unity 2D: Changing animation when player is in motion.
I am making a topdown 2D game that uses left click to move and I am wondering how to detect when the player is moving to switch animations from idle to walking.
using UnityEngine;
using System.Collections;
public class Player_Rig : MonoBehaviour
{
public float speed = 3.5f;
private Rigidbody2D rb2d;
private Animator anim;
private Vector3 target;
private Vector3 startPosition;
void Start()
{
rb2d = gameObject.GetComponent<Rigidbody2D>();
anim = gameObject.GetComponent<Animator>();
}
void Update()
{
startPosition = transform.localPosition;
if (Input.GetMouseButtonDown(0))
{
target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
target.z = transform.position.z;
if (target.x > transform.position.x) transform.localScale = new Vector3(5, 5, 5);
else if (target.x < transform.position.x) transform.localScale = new Vector3(-5, 5, 5);
anim.SetInteger("Direction", 1);
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
}
Comment
Answer by Endless_Aftermath · Jun 24, 2016 at 08:37 AM
How about a bool that tells whether or not the gameObject has reached its destination? Something along these lines...
bool isMoving=false;
if(Input.GetMouseButtonDown(0))
{
isMoving = true;
//all your code goes here
}
if(startPosition ==target)
{
isMoving = false;
}
if(isMoving)
{
Animation.Play(whateverYourAnimationIsCalled);
}
else
{
Animation.Stop(whateverYourAnimationIsCalled);
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How do I make my enemy have animations for directions during movemvent 1 Answer
Distribute terrain in zones 3 Answers
How to change animation's speed in C#? 2 Answers
Animation Not Playing - VideoExplanation 2 Answers