Unity 2D物体面向其移动的方向

Unity 2D object face direction its moving

大家好,我在使 2D 精灵面向其移动方向时遇到了问题。它们在地图上跟随 waypoints,我希望它们在穿过 waypoints 时旋转,但我无法实现它。如果您能帮上忙,我将不胜感激。

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

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];
        }
    }
}

将以下函数添加到您的脚本中并在更新中调用它

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);
}

如果旋转似乎不正确,只需将 'offset' 值调整 90 倍,或者完全删除它。