Unity——鼠标控制摄像机移动,(距离)缩放,旋转

如题,在此简单记录主要代码,使用时可以视情况自己再封装。

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RoScal : MonoBehaviour {

    public float xSpeed = 100;//旋转速度
    public float ySpeed = 100;
    public float yMinLimit = -20;//旋转限制
    public float yMaxLimit = 80;
    public float x = 0.0f;
    public float y = 0.0f;
    public float scroll = 3;
    public float axisraw = 10;

    void Start()
    {
        Vector2 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;

    }

    void Update()
    {
        if (Input.GetMouseButton(1))
        {
                x += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
                y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
        }
        Ctrl_Cam_Move();              
    }
     //镜头的远离和接近
    private void Ctrl_Cam_Move()
    {
        if (Input.GetMouseButton(0))
        {
            Vector3 p0 = Camera.main.transform.position;
            Vector3 p01 = p0 - Camera.main.transform.right * Input.GetAxisRaw("Mouse X") * axisraw * Time.timeScale;
            Vector3 p03 = p01 - Camera.main.transform.up * Input.GetAxisRaw("Mouse Y") * axisraw * Time.timeScale;
            Camera.main.transform.position = p03;
        }
        else
        {
            float wheel = Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * scroll;
            transform.Translate(Vector3.forward * wheel);
        }        
                   
    }

    public void LateUpdate()
    {
        y = ClampAngle(y, yMinLimit, yMaxLimit);
        Quaternion rotation = Quaternion.Euler(y, x, 0);
        transform.rotation = rotation;

    }

    /// <summary>
    /// Y值的限制
    /// </summary>
    float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360)
            angle += 360;

        if (angle > 360)
            angle -= 360;

        return Mathf.Clamp(angle, min, max);
    }
}
相关推荐
警醒与鞭策1 小时前
Codex桌面版与Claude桌面版使用设置
android·unity·ai·性能优化
xcLeigh2 小时前
Unity基础:Destroy与DestroyImmediate——正确销毁游戏物体的方式
游戏·unity·游戏引擎·教程
lllhhh_远方7 小时前
unity中URP场景阴影锯齿严重解决方案
unity·游戏引擎
沃普天科技8 小时前
100W 氮化镓充电器充电头扩展坞一体化设计,实用性翻倍
驱动开发·计算机外设·音视频·硬件工程·pcb工艺
小生凡一10 小时前
AI 是怎么学会用鼠标的?Computer Use工作原理
人工智能·计算机外设
淡海水11 小时前
07-06-源码-.NET Core GC的极致优化技术
unity·架构·c#·.netcore·gc·1024程序员节
野区捕龙为宠11 小时前
Unity 中使用 UnityWebRequest 加载 StreamingAssets 文件夹中的图片
unity·游戏引擎
走自己的路-雷龙12 小时前
体积显示器是什么?从成像原理到四类应用场景
计算机外设
北里闻箫13 小时前
推荐一款游戏引擎,一剑十八年引擎(YiJian18-Engine) - 跨平台2D/3D ECS 游戏引擎
3d·游戏引擎
淡海水1 天前
07-02-源码-.NET Core GC分配路径
算法·unity·c#·.netcore·gc·1024程序员节