Jimmy Musser
Jimmy Musser

Reputation: 63

Unity 2D object face direction its moving

Hey guys I'm having trouble making a 2D sprite face the direction it's moving. They follow waypoints on the map, and I want them to rotate as they move through the waypoints but am having trouble implementing it. If you could help I would appreciate it, thanks.

public class WaypointEnemy : MonoBehaviour
{
    public float speed = 5f;

    private Transform target;
    private int wavepointIndex = 0;
    private Rigidbody2D rigidBody;
    bool points = false;

    private void Start ( )
    {
        {
            int random = (Random.Range(-10, 10));
            if ( random >= 0 )
            {
                target = Waypoints.waypoints [ 0 ];
                points = true;
            }
            else
            {
                target = Waypoints2.waypoints2 [ 0 ];
            }
        }
    }

    void Update ( )
    {
        Vector2 dir = target.position - transform.position;
        transform.Translate ( dir.normalized * speed * Time.deltaTime, Space.World );
        if ( Vector2.Distance ( transform.position, target.position ) <= 0.4f )
        {
            GetNextWaypoint ( );
        }
    }

    void GetNextWaypoint ( )
    {
        if ( points == false )
        {
            wavepointIndex++;
            target = Waypoints.waypoints [ wavepointIndex ];
        }
        else
        {
            wavepointIndex++;
            target = Waypoints2.waypoints2 [ wavepointIndex ];
        }
    }
}

Upvotes: 1

Views: 4662

Answers (1)

Sean Carey
Sean Carey

Reputation: 807

Add the following function to your script and call it in Update:

private void RotateTowardsTarget()
{
    float rotationSpeed = 10f; 
    float offset = 90f;    
    Vector3 direction = target.position - transform.position;
    direction.Normalize();
    float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    Quaternion rotation = Quaternion.AngleAxis(angle + offset, Vector3.forward);
    transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
}

If the rotation seems off, just adjust the offset value by a factor of 90, or just remove it entirely.

Upvotes: 3

Related Questions