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

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

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. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-08 12:26:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-08 12:26:03       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-08 12:26:03       82 阅读
  4. Python语言-面向对象

    2023-12-08 12:26:03       91 阅读

热门阅读

  1. [C#]文件的读写-1

    2023-12-08 12:26:03       56 阅读
  2. zookeeper常用接口

    2023-12-08 12:26:03       51 阅读
  3. 二维码扫描并输出信息(小程序,IOS,安卓)

    2023-12-08 12:26:03       43 阅读
  4. 《微信小程序开发从入门到实战》学习四十四

    2023-12-08 12:26:03       59 阅读
  5. 数据结构-数组

    2023-12-08 12:26:03       56 阅读
  6. 搜索引擎高级用法总结: 谷歌、百度、必应

    2023-12-08 12:26:03       64 阅读
  7. stm8l151,c语言混编汇编,实现16位乘除法

    2023-12-08 12:26:03       52 阅读
  8. Flink 项目系列

    2023-12-08 12:26:03       70 阅读
  9. flink sink多个topic

    2023-12-08 12:26:03       50 阅读
  10. PTA 7-237 特殊排序

    2023-12-08 12:26:03       53 阅读
  11. Metasploit的提权和后渗透

    2023-12-08 12:26:03       46 阅读