项目中遇到要加一个Unity程序,而视角需要自由控制,然后又不能超出建模范围,不然就穿模了。
这里先通过方法读取键盘和鼠标,得到控制相机移动原始参数。
xL2, yL2, zL2为读取上一帧相机位置,xL, yL, zL,为移动后读取下一帧位置,靠近限制范围时,斜向走也不会卡住,判断移动方向的xyz轴分量哪个不超出移动限制范围,就让哪个分量生效。
说说其他不能用的方法:设定相机位置是可以用transform.position = new Vector3(x, y, z),但是这个坐标是相对于整个场景固定,不会随着视角转动而转动,控制就会乱。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraScript : MonoBehaviour
{
public int speed = 20;
float x1, y1, xL, yL, zL, xL2, yL2, zL2, xL3, yL3, zL3;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
float s = 0f;
if (Input.GetKey("space"))
{
s = 1;
}
if (Input.GetKey("left ctrl"))
{
s = -1;
}
x1 += Input.GetAxis("Mouse X");
y1 += -Input.GetAxis("Mouse Y");
transform.rotation = Quaternion.Euler(y1, x1, 0);
xL2 = transform.position.x;
yL2 = transform.position.y;
zL2 = transform.position.z;
transform.Translate(new Vector3(h, s, v) * Time.deltaTime * speed);
xL = transform.position.x;
yL = transform.position.y;
zL = transform.position.z;
if (xL > 199 || xL < -199)xL3 = xL2;
else xL3 = xL;
if (yL > 14 || yL < 0.5)yL3 = yL2;
else yL3 = yL;
if (zL > 49 || zL < -49)zL3 = zL2;
else zL3 = zL;
transform.position = new Vector3(xL3, yL3, zL3);
}
}