using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyLookAt : MonoBehaviour
{
public Transform target;
public Vector3 offset;
Transform chest;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void LateUpdate()
{
chest.LookAt(target.position);
ClampRotation(chest.rotation, new Vector3(0, 60, 0));
chest.rotation = chest.rotation * Quaternion.Euler(offset);
}
public static Quaternion ClampRotation(Quaternion q, Vector3 bounds)
{
q.x /= q.w;
q.y /= q.w;
q.z /= q.w;
q.w = 1.0f;
float angleX = 2.0f * Mathf.Rad2Deg * Mathf.Atan(q.x);
angleX = Mathf.Clamp(angleX, -bounds.x, bounds.x);
q.x = Mathf.Tan(0.5f * Mathf.Deg2Rad * angleX);
float angleY = 2.0f * Mathf.Rad2Deg * Mathf.Atan(q.y);
angleY = Mathf.Clamp(angleY, -bounds.y, bounds.y);
q.y = Mathf.Tan(0.5f * Mathf.Deg2Rad * angleY);
float angleZ = 2.0f * Mathf.Rad2Deg * Mathf.Atan(q.z);
angleZ = Mathf.Clamp(angleZ, -bounds.z, bounds.z);
q.z = Mathf.Tan(0.5f * Mathf.Deg2Rad * angleZ);
return q.normalized;
}
}
我尝试使用 ClampRotation 方法,但它什么也没做。如果目标在他身后,玩家的头部仍然可以旋转 360 度。我想将旋转限制在一些人性化的侧面,也可能是向上/向下。
我试过这个测试 Y(向上/向下)
Vector3 chestAngle = chest.eulerAngles;
chestAngle.y = (chestAngle.y > 180) ? chestAngle.y - 360 : chestAngle.y;
chestAngle.y = Mathf.Clamp(chestAngle.y, -50, 50);
chest.rotation = Quaternion.Euler(chestAngle);
但它夹住了 Z 而不是 Y。它夹住了左边而不是上/下。我要夹上/下和左/右
答案 0 :(得分:0)
您永远不会将固定值分配给旋转。
chest.rotation = ClampRotation(chest.rotation, new Vector3(0, 60, 0));
答案 1 :(得分:0)
忘记 ClampRotation
函数并尝试以下代码:
Vector3 chestAngle = chest.rotation.eulerAngles;
chestAngle.y = (chestAngle.y > 180) ? chestAngle.y - 360 : chestAngle.y;
chestAngle.y = Mathf.Clamp(chestAngle.y, -50 , 50);
chest.rotation = Quaternion.Euler(chestAngle);