using System.Collections; using System.Collections.Generic; using UnityEngine; public class Look2D : MonoBehaviour { [SerializeField] private Transform _targetPos; private void Update() { transform.eulerAngles = LookTargetAngle(transform, _targetPos.position); } public Vector3 LookTargetAngle(Transform playerTrans, Vector3 targetPos) { float dx = targetPos.x - playerTrans.transform.position.x; float dy = targetPos.y - playerTrans.transform.position.y; float rotationZ = Mathf.Atan2(dy, dx) * 180 / Mathf.PI; //得到最终的角度并且确保在 [0, 360) 这个区间内 rotationZ -= 90; //获取增加的角度 float originRotationZ = playerTrans.eulerAngles.z; float addRotationZ = rotationZ - originRotationZ; //超过 180 度需要修改为负方向的角度 if (addRotationZ > 180) { addRotationZ -= 360; } //应用旋转 return new Vector3(0, 0, playerTrans.eulerAngles.z + addRotationZ); } }