[英]Clamping problems with diagonal camera rotation around object based on mouse input
我正在編寫一個腳本,它圍繞播放器 object 對角旋轉相機(3D x 和 3D y 軸)。 輸入如下:
它可以工作,但是,我無法控制相機的 y 軸旋轉。 X 軸按預期工作。 觀看上面的視頻,看看最后的問題。 它在 y 軸上過度旋轉,因此相機以完全錯誤的方向朝向玩家。 也許有大腦功能的人可以想出一個解決方案? 太棒了,提前謝謝!
這是我的腳本:
void Update() {
mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
mouseY = -(Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime);
rotationXAxis += mouseY;
rotationXAxis = ClampAngle(rotationXAxis, -30f, 30f);
float rotationYAxis = rotationXAxis;
rotationYAxis = ClampAngle(rotationYAxis, 0f, 30f);
Quaternion fromRotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, 0);
Quaternion toRotation = Quaternion.Euler(rotationXAxis, transform.rotation.eulerAngles.y - rotationYAxis * Time.deltaTime, 0);
Quaternion rotation = toRotation;
Vector3 negDistance = new Vector3(xPosOffset, yPosOffset, -distance);
Vector3 position = rotation * negDistance + player.position;
transform.rotation = rotation;
transform.position = position;
player.Rotate(Vector3.up * mouseX);
mouseY = Mathf.Lerp(mouseY, 0, Time.deltaTime);
}
float ClampAngle(float angle, float min, float max) {
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp(angle, min, max);
}
我試着用偽語言解釋你。
正弦和余弦基本相同,但偏移了 90 度。
這個 function 正在生產的是 -1.. 1 個數字是 -100%.. 100%
基本上你需要的是
var _x,_y,_z; //original position
var deg; // 0..360
x = _x * sin(deg);
y = _y * cos(deg);
z = _z;
這是圍繞世界旋轉 [0,0,0]
如果你想繞另一個軸旋轉
var a_x,a_y,a_z;
x = _x + a_x * sin(deg);
y = _y + a_y * cos(deg);
z = _z + a_z;
最大的關鍵是保留默認位置 [_x,_y,_z] 不要犯這個錯誤
x = x * sin(deg);
准確地說是一個矩陣
_x _y _z
x [cos -sin 0]
y [sin cos 0]
z [0 0 1]
x = _x * cos(deg) + _y * -sin(deg) + _z * 0;
y = _x * sin(deg) + _y * cos(deg) + _z * 0;
z = _x * 0 + _y * 0 + _z * 1;
查看您的軸的 3d 矩陣。 https://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions
嘗試這樣的事情
void Update(Player player) {
_position = player.position;
mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
mouseY = -(Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime);
_delta_x = mouseX - _position.x;
_delta_y = mouseY - _position.y;
_delta_z = 0;
_rot_x = ClampAngle(mouseX, mouseY, -30f, 30f);
_rot_y = ClampAngle(mouseX, mouseY, -30f, 30f);
_rot_z = 0;
Vector3 position = new Vector3(_delta_x, _delta_y, _delta_z);
position = position.rotate (rot_x, rot_y, rot_z);
position = position.add(_position.x,_position.y,_position.z);
player.position = position;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.