- Home /
4 direction animation unity 2d
I'm doing a 2d game where the character walks in four directions but I do not know how to make him change the sprite depending on which direction he goes (sorry if it's not well written I do not speak English)
Answer by Comini2 · Mar 01, 2018 at 08:07 PM
You need to change the rotation of the transform based on his movement, something like this:
if (Input.GetAxis("Horizontal") > 0)
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
transform.rotation = Quaternion.Euler(0, 0, 90f);
}
I do not want to rotate the character I just want him to run a different animation depending on the direction he's going
Oh, lol! Sorry, i didn't read it properly. But, if you have a animation called "right-animation" on your animator, you could do it like this, don't you ?
if (Input.GetAxis("Horizontal") > 0)
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
anim.Play("right-animation");
}
Answer by viber-tron · Mar 01, 2018 at 07:54 PM
this is the player script
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Player : MonoBehaviour {
private Animator anim;
public Transform player;
public float speed;
// Use this for initialization
void Start () {
anim = player.GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
Move();
}
void Move()
{
if (Input.GetAxis("Horizontal") > 0)
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
if (Input.GetAxis("Horizontal") < 0)
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
}
if (Input.GetAxis("Vertical") > 0)
{
transform.Translate(Vector2.up * speed * Time.deltaTime);
}
if (Input.GetAxis("Vertical") < 0)
{
transform.Translate(Vector2.down * speed * Time.deltaTime);
}
}
}
Answer by Chik3r · Mar 01, 2018 at 08:20 PM
Animator.SetBool("GoingUp", true); // When he is going up
Animator.SetBool("GoingDown", true); // When he is going down, etc.
Your answer
Follow this Question
Related Questions
,Spawning snow or changing tilesets to snow as the player walks past them 0 Answers
Best approach for 2d animation to interact with the environment? 0 Answers
Shooter 2D: Character animation only runs once 1 Answer
How to keep Diagonal Movement Direction in 2D Isometric game? 0 Answers
,Is there a Way to Flip 2D-Keyframes? 0 Answers