【Unity3D】使用鼠标键盘控制Camera视角(即时战略类游戏视角):缩近,拉远,旋转

今天写一个demo,要用到鼠标键盘控制三维视角,因此写了个脚本用于控制。

该脚本可以用于即时战略类游戏的视角,提供了缩进,拉伸,旋转。同时按住鼠标右键不放,移动鼠标可以实现第一人称视角的效果。

 

复制代码
 1 using UnityEngine;
 2 using System.Collections;
 3 
 4 public class CameraController : MonoBehaviour {
 5 
 6 
 7     public float near = 20.0f;
 8     public float far = 100.0f;
 9 
10     public float sensitivityX = 10f;
11     public float sensitivityY = 10f;
12     public float sensitivetyZ = 2f;
13     public float sensitivetyMove = 2f;
14     public float sensitivetyMouseWheel = 2f;
15 
16 
17     void Update () {
18         // 滚轮实现镜头缩进和拉远
19         if (Input.GetAxis("Mouse ScrollWheel") != 0)
20         {
21             this.camera.fieldOfView =this.camera.fieldOfView - Input.GetAxis("Mouse ScrollWheel")*sensitivetyMouseWheel;
22             this.camera.fieldOfView = Mathf.Clamp(this.camera.fieldOfView, near, far);
23         }
24         //鼠标右键实现视角转动,类似第一人称视角
25         if (Input.GetMouseButton(1))
26         { 
27             float rotationX = Input.GetAxis("Mouse X") * sensitivityX;
28             float rotationY = Input.GetAxis("Mouse Y") * sensitivityY;
29             transform.Rotate(-rotationY, rotationX, 0);            
30         }
31 
32         //键盘按钮←和→实现视角水平旋转
33         if (Input.GetAxis("Horizontal")!=0)
34         {
35             float rotationZ=Input.GetAxis("Horizontal") * sensitivetyZ;
36             transform.Rotate(0, 0, rotationZ); 
37         }
38     }
39 }
复制代码

 

直接把脚本拖到摄像机上就可以使用了~

posted @   H5开发技术  阅读(15799)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示