我试图用空格键改变主摄像机的位置和旋转。 要改变位置我没有问题,但发现问题是在z轴上旋转相机。 最初旋转设置为359.9f,按空格键后旋转设置为179.9f,但当我返回原始旋转(359.9f)时,旋转方向不同。
这是我的代码:
using UnityEngine;
using System.Collections;
public class Untitled : MonoBehaviour {
//Lerp Position
private Vector3 start;
private Vector3 end;
//Lerp Time
private float lerpTime = 3f;
private float currentLerpTime = 0;
// Camera Up - Down
public bool up = false;
void Update () {
start = Camera.main.transform.position;
end = new Vector3 (Camera.main.transform.position.x, 105, Camera.main.transform.position.z);
//Quaternions
Quaternion RotationA = Quaternion.Euler (0, 0, 179.9f);
Quaternion RotationB = Quaternion.Euler (0,0, 359.9f);
// Inputs
if (Input.GetKey (KeyCode.Space) && Camera.main.transform.position.y < 8f)
{
up = true;
currentLerpTime = 0;
lerpTime = 3f;
}
if (Input.GetKey (KeyCode.Space) && Camera.main.transform.position.y > 103f)
{
up = false;
currentLerpTime = 0;
lerpTime = 3f;
}
// When the camera is down (Lerp/Slerp)
if (up == false)
{
currentLerpTime += Time.deltaTime;
if (currentLerpTime >= lerpTime)
{
currentLerpTime = lerpTime;
}
float Perc = currentLerpTime / lerpTime;
start = Camera.main.transform.position;
Camera.main.transform.position = Vector3.Lerp (start, new Vector3 (Camera.main.transform.position.x, 105, Camera.main.transform.position.z), Perc);
Camera.main.transform.rotation = Quaternion.Slerp (Camera.main.transform.rotation, RotationA, Perc);
}
// When the camera is up (Lerp/Slerp)
if (up == true)
{
currentLerpTime += Time.deltaTime;
if (currentLerpTime >= lerpTime)
{
currentLerpTime = lerpTime;
}
float Perc = currentLerpTime / lerpTime;
end = Camera.main.transform.position;
Camera.main.transform.position = Vector3.Lerp (end, new Vector3(Camera.main.transform.position.x, 6, Camera.main.transform.position.z), Perc);
Camera.main.transform.rotation = Quaternion.Slerp (Camera.main.transform.rotation, RotationB, Perc);
}
}
}
我还尝试了另一种旋转方法,但没有任何改变:
Camera.main.transform.rotation = Quaternion.Slerp (Camera.main.transform.rotation, Quaternion.AngleAxis(179.9f, Vector3.forward), Perc)
Camera.main.transform.rotation = Quaternion.Slerp (Camera.main.transform.rotation, Quaternion.AngleAxis(359.9f, Vector3.forward), Perc)
我该如何解决?提前谢谢。
答案 0 :(得分:0)
你的程序所做的是在两次旋转之间交替,这两次旋转占球体旋转的一半。为达到理想的效果,第二次旋转应朝向0角。在您当前的程序中,它会旋转回360度。
目前如何运作:
1.第一次旋转359.9f - > 179.9f(浮动减少)
2.第二次旋转179.9f - > 359.9f(浮动增加)
3.(从1开始重复。)
您认为它应该如何运作:
1.第一次旋转359.9f - > 179.9f(浮动减少)
2.第二次旋转179.9f - > 0.0f(浮点数减少,当值达到零时可能重置为359.9f)
要遵循您的编码风格,只需添加一个轮换:
//Quaternions
Quaternion RotationA = Quaternion.Euler (0, 0, 179.9f);
Quaternion RotationB = Quaternion.Euler (0,0, 359.9f);
Quaternion RotationC = Quaternion.Euler (0,0, 0.0f);
然后更改另一个旋转以使用RotationC
// When the camera is up (Lerp/Slerp)
if (up == true)
{
...
(Camera.main.transform.rotation, RotationC, Perc);
}
最后在旋转到零时重置为默认值:
void Update () {
if(Camera.main.transform.rotation == RotationC){
Camera.main.transform.rotation = RotationB;
}
}