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);
    }
}
相关推荐
mxwin9 小时前
Unity URP 半透明阴影的局限性
unity·游戏引擎
空中海10 小时前
第四篇:Unity高级阶段(架构级开发能力)
unity·架构·游戏引擎
小贺儿开发11 小时前
【MediaPipe】Unity3D 虚拟面具互动演示
unity·人机交互·shader·摄像头·面具·互动·脸部捕捉
DaLiangChen12 小时前
Unity URP 绘制参考网格 Shader 教程(抗锯齿 + 渐变淡出)
unity·游戏引擎
空中海13 小时前
第三篇:Unity进阶阶段(商业项目能力)
unity·游戏引擎
私人珍藏库15 小时前
Windows桌面工具箱 滴哦小精灵 v1.5.0
计算机外设·工具·软件·win·多功能
Yuk丶17 小时前
Procedural Dialogue Engine - UE4程序化对话系统的技术实现
c++·游戏引擎·ue4·游戏程序·虚幻
RReality18 小时前
【Unity Shader URP】屏幕空间扭曲后处理(Screen Space Distortion)实战教程
ui·unity·游戏引擎·图形渲染·材质
YJlio19 小时前
1 4.1 微软商店的使用(Microsoft Store:下载/安装/管理应用与游戏)
运维·hive·hadoop·windows·游戏·microsoft·计算机外设
zcc85807976220 小时前
Unity 事件驱动架构
unity