Home:ALL Converter>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?

Ask Time:2022-11-25T01:10:49         Author:EPiedrahita

Json Formatter

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

Author:EPiedrahita,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/74564266/how-do-i-flip-the-sprite-of-my-npc-to-face-the-direction-it-is-moving
yy