Hedy guys, I am new to Unity and scripting and am working on developing a 2D top down style game. I have the animations and movement good to go but I am struggling with getting the character to face the last direction of movement when idle. I can’t seem to figure it out. Here is the movement code I have:
public class Movescriipt : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
public Animator animator;
Vector2 movement;
// Update is called once per frame
void Update()
{
movement.x = UnityEngine.Input.GetAxisRaw("Horizontal");
movement.y = UnityEngine.Input.GetAxisRaw("Vertical");
animator.SetFloat("Horizontal" , movement.x);
animator.SetFloat("Vertical", movement.y);
animator.SetFloat("Speed", movement.sqrMagnitude);
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
}
You add new behaviour you have not previously asked for and say the code I provided that gives you what you originally asked for doesn’t work?
As I hope you can see in the example I provided, when there’s no input, it doesn’t change the direction so…
… the code I provided just does that because when there is no input, there’s no direction from the input. If you want a specific direction when that’s the case then add the code there.
If you are asking for others to write code for you as you add behaviours you need then that’s not what the forum is for.
So to be clear, you want to choose one of 4 directions and set your sprite/animation accordingly?
If so, the basic idea is…
using UnityEngine;
public class FaceDirection : MonoBehaviour
{
public float moveSpeed = 5f;
public enum Facing
{
Idle,
Left,
Right,
Up,
Down
}
private Vector2 movement;
private Rigidbody2D rb;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
var facing = GetFacing();
/* Change the animation or whatever here based upon the current direction */
}
private Facing GetFacing()
{
if (movement.x < 0f)
return Facing.Left;
if (movement.x > 0f)
return Facing.Right;
if (movement.y < 0f)
return Facing.Down;
if (movement.y > 0f)
return Facing.Up;
return Facing.Idle;
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
}
There are far better ways of doing this stuff depending on your experience with Unity and other requirements (maybe 8 directions etc) but this is the basic idea made as simple as possible.
Maybe you want something else, hard to say for sure.