Unity实现摄像机视角上下左右移动(固定旋转角的z值)

网上找了很多都没有看到保持z值不变的方法,自己写了一下:

将下面这个脚本绑到摄像机运行就可。


using UnityEngine;
public class CameraMove : MonoBehaviour
{
    public float rotateSpeed = 3.5f;//摄像机旋转速度。
    public float moveSpeed = 3.5f;//摄像机移动速度。
    private bool isRotate;
    void Update()
    {
        CameraRotateView();
        Move();
    }
    //按下左键镜头跟随鼠标移动,松开不移动
    void CameraRotateView()
    {
        if (Input.GetMouseButtonUp(0))
            isRotate = false;
        if (Input.GetMouseButtonDown(0))
            isRotate = true;
       
        if (isRotate)
        {
            float swipeUpOrDown = rotateSpeed * Input.GetAxis("Mouse Y");
            float swipeLeftAndRight = rotateSpeed * Input.GetAxis("Mouse X");

            if (Mathf.Abs(swipeUpOrDown) < Mathf.Abs(swipeLeftAndRight))
            {
                //向右滑动时正值,向左滑动是负值。
                transform.RotateAround(transform.position, Vector3.up, swipeLeftAndRight);
            }
            else
            {
                //使用自身的x轴作为旋转轴,这样保证z轴不会发生数值变化
                transform.RotateAround(transform.position, transform.right, -swipeUpOrDown);
            }
        }
    }
    void Move()
    {
        float beforeOrAfter = Input.GetAxis("Horizontal");
        float swipeLeftAndRight = Input.GetAxis("Vertical");
        transform.position += transform.forward * swipeLeftAndRight * Time.deltaTime*moveSpeed;
        transform.position += transform.right * beforeOrAfter * Time.deltaTime*moveSpeed;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值