最近的项目中遇到了一个需求:要求能全方位并细致的观察物体。
一开始我的想法是物体旋转,然后相机能够缩放视角,
于是立马着手写出了以下的代码:
float x;
float y;
float xSpeed;
float ySpeed;
private void Update()
{
if (Input.GetMouseButton(0)) //一般是鼠标右键控制,但是工程要打包成Web版本按键会有冲突所以此处用鼠标左键
{
x = Input.GetAxis("Mouse X") * xSpeed;
y = Input.GetAxis("Mouse Y") * ySpeed;
transform.Rotate(new Vector3(y, x, 0),Space.World); //此处遇到了问题,如果没有Space.World物体旋转180度之后旋转轴会反向旋转
} else if (Input.GetAxis("Mouse ScrollWheel") != 0)
{
float ViewValue=0;
if (ViewValue< 0)
{
//范围值限定
if (Camera.main.fieldOfView <= 100)
Camera.main.fieldOfView += 2;
if (Camera.main.orthographicSize <= 20)
Camera.main.orthographicSize += 0.5F;
}
//Zoom in
if (ViewValue > 0)
{
//范围值限定
if (Camera.main.fieldOfView > 2)
Camera.main.fieldOfView -= 2;
if (Camera.main.orthographicSize >= 1)
Camera.main.orthographicSize -= 0.5F;
}
}
}
但是经过测试之后发现效果不是很好,尤其是在两个轴分量都有的时候,所以我决定只用鼠标的X轴分量,Y轴的旋转用键盘按键来控制,注意这里的LookAt方法,可以让摄像机在旋转的同时一直对准要观察的物体:
void Update()
{
if (Input.GetMouseButton(0))
{
RotateRenTi(Input.GetAxis("Mouse X"));
RotCam(Input.GetAxis("Mouse Y"));
} else if (Input.GetAxis("Mouse ScrollWheel") != 0)
{
float ViewValue=0;
if (ViewValue< 0)
{
//范围值限定
if (Camera.main.fieldOfView <= 100)
{
Camera.main.fieldOfView += 2;
}
else if (Camera.main.orthographicSize <= 20)
{
Camera.main.orthographicSize += 0.5F;
}
}
//Zoom in
else if (ViewValue > 0)
{
//范围值限定
if (Camera.main.fieldOfView > 2)
{
Camera.main.fieldOfView -= 2;
}else if (Camera.main.orthographicSize >= 1)
{
Camera.main.orthographicSize -= 0.5F;
}
}
}
Camera.main.transform.LookAt(GameObject.Find("ZJZY_RenTi0_Dian07_05").transform);
if (Input.GetKey(KeyCode.UpArrow))
{
UpKeyDown();
}
if (Input.GetKey(KeyCode.DownArrow))
{
DownKeyDown();
}
private void UpKeyDown()
{
Camera.main.transform.Translate(Vector3.up * -0.01f);
}
private void DownKeyDown()
{
Camera.main.transform.Translate(Vector3.up * 0.01f);
}
private void RotCam()
{
Camera.main.transform.Rotate(new Vector3(1,0,0) *RotCam*20f, Time.deltaTime *20f);
}
}
至此,能够细致观察物体的功能完成,经过测试发现效果还算不错。
本人小菜鸟,如果您有不明白的地方,或者是有更好的方法,请私信联系我,本人将不胜感激。
感谢阅读。