Home > Back-end >  How do I flip the sprite of my NPC to face the direction it is moving?
How do I flip the sprite of my NPC to face the direction it is moving?

Time:11-28

I'm building a simple 2D platformer and have an NPC that all it does is walk back and forth, left and right in the background. To do this I followed a tutorial for an object moving back and forth between waypoints so the movement part is working.

What I can't figure out is how to flip the sprite so it is facing the direction it is moving in.

This is the code I have for the object moving between waypoints:

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

public class WaypointFollower : MonoBehaviour
{
    [SerializeField] private GameObject[] waypoints;

    private int currentWaypointIndex = 0;

    [SerializeField] private float speed = 2f;

    private void Update()
    {
        if(Vector2.Distance(waypoints[currentWaypointIndex].transform.position, transform.position) < .1f)
        {
            currentWaypointIndex  ;

            if (currentWaypointIndex >= waypoints.Length)
            {
                currentWaypointIndex = 0;
            }
        }

        transform.position = Vector2.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, Time.deltaTime * speed);

    }

}

I don't really know how to check for the objects movement and direction since all tutorials I have found for this usually do it around player input.

Any help is greatly appreciated

CodePudding user response:

Your code already moves the NPC. And by adding a few more lines of code, we can determine the direction, left or right, that the NPC is moving.

In this code, we’ll expose an object field for you to drag in the NPCs sprite renderer. An alternative would be to search for it in the code.

public class WaypointFollower : MonoBehaviour
{
    [SerializeField] private GameObject[] waypoints;
    private int currentWaypointIndex = 0;
    [SerializeField] private float speed = 2f;
    [SerializeField] SpriteRenderer _renderer;

    private void Update()
    {
        if(Vector2.Distance(waypoints[currentWaypointIndex].transform.position, transform.position) < .1f)
            if (  currentWaypointIndex >= waypoints.Length)
                currentWaypointIndex = 0;

        var x0 = transform.position.x;
        var x1 = waypoints[currentWaypointIndex].transform.position.x;
        // let’s assume your sprite is facing right by default. In which case, we want to flip if the NPC is moving left.
        _renderer.FlipX = x0 > x1;

        transform.position = Vector2.MoveTowards(transform.position, waypoints[currentWaypointIndex].transform.position, Time.deltaTime * speed);
    }
}
  • Related