【Unity代码片段】镜头控制


前言

镜头控制功能代码记录。


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(空格)重定位镜头中央到角色

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值