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);
    }
}
相关推荐
shandianchengzi43 分钟前
【记录】Unity|Unity从安装到打开一个Github项目(以我的世界(仿)为例)
unity·c#·游戏引擎·github·我的世界·mc
yi碗汤园14 小时前
【超详细】C#自定义工具类-StringHelper
开发语言·前端·unity·c#·游戏引擎
野奔在山外的猫16 小时前
【案例】Unity 平台访问文件浏览器(汇总)
unity
林恒smileZAZ21 小时前
CSS3 超实用属性:pointer-events (可穿透图层的鼠标事件)
前端·计算机外设·css3
WaWaJie_Ngen1 天前
【OpenGL】模板测试(StencilTest)
c++·算法·游戏·游戏引擎·游戏程序·图形渲染
开发游戏的老王2 天前
虚幻引擎虚拟制片入门教程目录
游戏引擎·虚幻
future_studio2 天前
聊聊 Unity(小白专享、C# 小程序 之 自动更新)
unity·小程序·c#
心疼你的一切2 天前
Unity开发利器:ScriptableObject的数据容器设计与内存优化原理
microsoft·unity·c#·游戏引擎
至善迎风2 天前
将跨平台框架或游戏引擎开发的 Windows 应用上架 Microsoft Store
windows·microsoft·游戏引擎
worxfr2 天前
小游戏引擎架构设计案例分析
游戏引擎