【问题标题】:Unity 2D object face direction its movingUnity 2D对象面方向其移动
【发布时间】:2019-01-20 19:12:39
【问题描述】:

大家好,我无法让 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];
        }
    }
}

【问题讨论】:

    标签: unity3d rotation 2d quaternions


    【解决方案1】:

    将以下函数添加到您的脚本中并在 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 倍,或者将其完全移除。

    【讨论】:

    • 谢谢,我一直在努力弄清楚。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    相关资源
    最近更新 更多