首页 > 解决方案 > Unity 2D对象面方向其移动

问题描述

嘿伙计们,我无法让 2D 精灵面向它移动的方向。他们跟随地图上的航路点,我希望他们在通过航路点时旋转,但在实施时遇到了麻烦。如果您能帮上忙,我将不胜感激,谢谢。

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

标签: unity3drotation2dquaternions

解决方案


将以下函数添加到您的脚本并在 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);
}

如果旋转似乎关闭,只需将“偏移”值调整 90 倍,或者完全删除它。


推荐阅读