unity3D实现自由视角

一、实现目标

  在场景中移动相机,达到自由观察场景的效果。

具体功能实现:

1.X轴和Z轴的水平移动

 2.当鼠标右键被按下时,相机旋转

二、实现步骤

The First Step:创建一个Camera:

        

The Second Step:脚本实现

创建C#脚本 -- FreeCameraController         

              

using UnityEngine;

public class FreeCameraController : MonoBehaviour
{
    public float moveSpeed = 4.0f; // 相机移动速度
    public float mouseSensitivity = 4.0f; // 鼠标旋转灵敏度

    private Vector3 moveDirection = Vector3.zero;//初始化相机向量为0向量
    private float xRotation = 0f;

    void Update()
    {
        // 移动:结合水平和垂直输入计算相机移动方向
        //horizontal 和 vertical 接收Input.GetAxis()返回的一个介于-1 到 1的数值
        //表示方向和强度
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        // 注意这里我们直接使用transform,因为脚本假设挂载在相机上
        //transform.right 返回的是相机对象本地坐标系的右侧方向向量。x- Axis
        //transform.forward 返回的是相机对象本地坐标系的前方方向向量 y- Axis
        moveDirection = transform.right * horizontal + transform.forward * vertical;
        moveDirection *= moveSpeed * Time.deltaTime; // 根据时间增量调整移动距离以保持恒定速度
        //print("moveDirection" + moveDirection);
        transform.position += moveDirection; // 应用移动
        //print("transform" + transform.position);

        // 旋转:当鼠标右键被按下时,允许相机旋转

        if (Input.GetMouseButton(1))
        {
            // 获取鼠标水平和垂直移动量,并应用旋转
            float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
            float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

            // 限制x轴旋转(俯仰)在-90到90度之间,防止翻转
            xRotation -= mouseY;
            xRotation = Mathf.Clamp(xRotation, -90f, 90f);

            // 直接使用transform来旋转相机,简化代码并移除对cameraTransform的依赖
            transform.localRotation = Quaternion.Euler(xRotation, transform.localEulerAngles.y + mouseX, 0f);
            // 注意:上面一行同时处理了x轴(俯仰)和y轴(偏航),简化了旋转逻辑
        }
        
    }
}

        

注:如需修改输入方式,此处Input.GetAxis("Horizontal")和Input.GetAxis("Vertical")中的字符串参数应与Edit - ProjectSettings - InputManager中的参数名一致

将C#脚本 -- FreeCameraController添加到Camera身上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值