前言
镜头控制功能代码记录。
1 鼠标中键拖拽移动
使用鼠标位移量修改镜头位置。
// CameraDragSpeed 控制拖拽速度
// mMainCamera 被控制的摄像机
// mLastMousePosition 拖拽前鼠标位置
private void DrawMove()
{
if (Input.GetMouseButtonDown(2))
{
mLastMousePosition = Input.mousePosition;
}
if (Input.GetMouseButton(2))
{
mMainCamera.transform.position += (mLastMousePosition - Input.mousePosition) * CameraDragSpeed * Time.deltaTime;
mLastMousePosition = Input.mousePosition;
}
}
2 鼠标贴边和方向键移动镜头
// mCameraAreaOffset 鼠标贴边触发范围
// mSpeed 镜头移动速度
void MoveCamera()
{
Vector2 mousePos = Input.mousePosition;
// 方向键移动量
var moveInput =
new Vector2(Input.GetAxisRaw("Horizontal"),
Input.GetAxisRaw("Vertical"));
// 加入鼠标移动量
if (mousePos.x > Screen.width * (1 - mCameraAreaOffset) && mousePos.x < Screen.width + 10)
moveInput.x = 1;
else if (mousePos.x < Screen.width * mCameraAreaOffset && mousePos.x > -10)
moveInput.x = -1;
if (mousePos.y > Screen.height * (1 - mCameraAreaOffset) && mousePos.y <= Screen.height + 10) moveInput.y = 1;
else if (mousePos.y < Screen.height * mCameraAreaOffset && mousePos.y >= -10) moveInput.y = -1;
// 应用
mMainCamera.transform.position -=
Time.deltaTime * new Vector3(moveInput.x, 0, moveInput.y) * mSpeed;
}
3 鼠标滚轮缩放镜头
镜头透视有两种,下面修改最大和最小缩放
3.1 正交投影
// mMaxSize,mMaxSize缩放最大最小限制
private void ScaleOrthographicSize()
{
//Zoom out
if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
if (mMainCamera.orthographicSize < mMaxSize)
mMainCamera.orthographicSize += mGameConfig.CameraScrollSpeed;
}
//Zoom in
if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
if (mMainCamera.orthographicSize > mMinSize)
mMainCamera.orthographicSize -= mGameConfig.CameraScrollSpeed;
}
}
3.2 透视投影
// mMaxSize,mMaxSize缩放最大最小限制
private void ScaleFOV()
{
//Zoom out
if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
if (mMainCamera.fieldOfView <= mMaxSize)
mMainCamera.fieldOfView += 2;
}
//Zoom in
if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
if (mMainCamera.fieldOfView > mMaxSize)
mMainCamera.fieldOfView -= 2;
}
}
4 锁定镜头到角色
void FollowPlayer()
{
if (mPlayerUnit == null) return;
Vector3 offset = new Vector3(0, 0, mMainCamera.transform.position.y * 0.3f);
Vector3 newCameraPosition = new Vector3(
mPlayerUnit.transform.position.x,
mMainCamera.transform.position.y,
mPlayerUnit.transform.position.z);
mMainCamera.transform.position = newCameraPosition + offset;
}
加上一些判断就可以做到Y解锁/锁定镜头到角色,Space(空格)重定位镜头中央到角色。