今天跟着Joe老师学习了在3D场景中进行场景移动的两种方法
摄像机移动方法
最基本的移动方式
通过GetAxisRaw实现摄像机的水平移动
moveInput.Set(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
在鼠标移动至界面边缘时也会移动:
if (mousePos.x > Screen.width * 0.9f && mousePos.x < Screen.width)
moveInput.x = 1;
if (mousePos.x < Screen.width * 0.1f && mousePos.x > 0)
moveInput.x = -1;
if (mousePos.y > Screen.height * 0.9f && mousePos.y < Screen.height)
moveInput.z = 1;
if (mousePos.y < Screen.height * 0.1f && mousePos.y > 0)
moveInput.z = -1;
设定相机移动的范围
//相机的范围
pos.x = Mathf.Clamp(pos.x, -10, 10);
pos.y = Math.Clamp(pos.y, 5, 30);
pos.z = Math.Clamp(pos.z, -25, 5);
transform.position = pos;
以下方法都是通过父级挂载子级的摄像机进行交互
方法一(通过键盘交互)
水平移动
//通过4个方向键进行水平移动
if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
{
newPos += transform.forward * panSpeed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
{
newPos -= transform.forward * panSpeed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))
{
newPos += transform.right * panSpeed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))
{
newPos -= transform.right * panSpeed * Time.deltaTime;
}
旋转
//Q,E进行旋转
if (Input.GetKey(KeyCode.Q))
{
Debug.Log("Q");
newRotation *= Quaternion.Euler(Vector3.up * rotationAmount);
}
if (Input.GetKey(KeyCode.E))
{
Debug.Log("E");
newRotation *= Quaternion.Euler(Vector3.down * rotationAmount);
}
放缩
//R,F 进行放缩
if (Input.GetKey(KeyCode.R))
{
Debug.Log("R");
newZoom += zoomAmount;
}
if (Input.GetKey(KeyCode.F))
{
Debug.Log("F");
newZoom -= zoomAmount;
}
执行完这些代码后记得将变化过参数重新赋值给gameobj
transform.position = Vector3.Lerp(transform.position, newPos, moveTime * Time.deltaTime);
transform.rotation = Quaternion.Lerp(transform.rotation, newRotation, moveTime * Time.deltaTime);
cameraTrans.localPosition = Vector3.Lerp(cameraTrans.localPosition, newZoom, moveTime * Time.deltaTime);
Lerp
通过差值函数将值的变化进行缓冲
但是 插值只能在[0,1]之间
Quaternion .Euler(四元数 欧拉)
V3.up
V3.down
方法二
鼠标交互
主要是通过点击与拖动之间的差值进行位移
private void HandleMouseInput()
{
if (Input.GetMouseButtonDown(1))
{
Plane plane = new Plane(Vector3.up,Vector3.zero);
float distance;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out distance))
{
dragStartPos = ray.GetPoint(distance);
}
}
if (Input.GetMouseButton(1))
{
Plane plane = new Plane(Vector3.up,Vector3.zero);
float distance;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out distance))
{
dragCurrentPos = ray.GetPoint(distance);
Vector3 difference = dragStartPos - dragCurrentPos;
newPos = transform.position +difference;
}
}
newZoom += Input.mouseScrollDelta.y * zoomAmount;
if (Input.GetMouseButtonDown(2))
{
rotateStart = Input.mousePosition;
}
if (Input.GetMouseButton(2))
{
RotateCurrent = Input.mousePosition;
Vector3 difference = rotateStart - RotateCurrent;
rotateStart = RotateCurrent;
newRotation *= quaternion.Euler(Vector3.up * -difference.x/320 );
}
}