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);
    }
}
相关推荐
胜天半子_王二_王半仙2 小时前
godot源码编译
游戏引擎·godot
Thomas_YXQ2 小时前
Unity3D IK解算器技术分析
开发语言·搜索引擎·unity·全文检索·unity3d·lucene
Tandy12356_3 小时前
Godot开发2D冒险游戏——第二节:主角光环整起来!
游戏引擎·godot
星火撩猿10 小时前
常见游戏引擎介绍与对比
unity·ue5·游戏引擎·godot
剁椒排骨11 小时前
win11什么都不动之后一段时间黑屏桌面无法显示,但鼠标仍可移动,得要熄屏之后才能进入的四种解决方法
运维·windows·经验分享·计算机外设·win11·win10
sky_smile_Allen11 小时前
[Unity]-[UI]-[Prefab] 关于Unity UGUI 的布局及组件讲解
ui·unity·游戏引擎
虾球xz13 小时前
游戏引擎学习第244天: 完成异步纹理下载
c++·学习·游戏引擎
iFlyCai13 小时前
对Mac文字双击或三击鼠标左键没有任何反应
macos·计算机外设
伊织code14 小时前
BongoCat - 跨平台键盘猫动画工具
计算机外设·动画·键盘·bongocat
太妃糖耶16 小时前
URP-利用矩阵在Shader中实现物体的平移和缩放
unity·矩阵