Unity3D鼠标控制摄像机“左右移动控制视角+WASD键盘控制前后左右+空格键抬升高度”脚本
//键盘控制
using UnityEngine; using System.Collections; public class CameraControl : MonoBehaviour { // Use this for initialization private GameObject gameObject; float x1; float x2; float x3; float x4; void Start () { gameObject = GameObject.Find ("Main Camera"); } // Update is called once per frame void Update () { //空格键抬升高度 if (Input.GetKey (KeyCode.Space)) { transform.position = new Vector3(transform.position.x,transform.position.y + 1,transform.position.z); } //w键前进 if(Input.GetKey(KeyCode.W)) { this.gameObject.transform.Translate(new Vector3(0,0,50*Time.deltaTime)); } //s键后退 if(Input.GetKey(KeyCode.S)) { this.gameObject.transform.Translate(new Vector3(0,0,-50*Time.deltaTime)); } //a键后退 if(Input.GetKey(KeyCode.A)) { this.gameObject.transform.Translate(new Vector3(-10,0,0*Time.deltaTime)); } //d键后退 if(Input.GetKey(KeyCode.D)) { this.gameObject.transform.Translate(new Vector3(10,0,0*Time.deltaTime)); } } }
鼠标移动视角
using UnityEngine; using System.Collections; [AddComponentMenu("Camera-Control/Mouse Look")] public class MouseLook : MonoBehaviour { public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 } public RotationAxes axes = RotationAxes.MouseXAndY; public float sensitivityX = 15F; public float sensitivityY = 15F; public float minimumX = -360F; public float maximumX = 360F; public float minimumY = -60F; public float maximumY = 60F; float rotationY = 0F; void Update () { if (axes == RotationAxes.MouseXAndY) { float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX; rotationY += Input.GetAxis("Mouse Y") * sensitivityY; rotationY = Mathf.Clamp (rotationY, minimumY, maximumY); transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0); } else if (axes == RotationAxes.MouseX) { transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0); } else { rotationY += Input.GetAxis("Mouse Y") * sensitivityY; rotationY = Mathf.Clamp (rotationY, minimumY, maximumY); transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0); } } void Start () { // Make the rigid body not change rotation if (GetComponent<Rigidbody>()) GetComponent<Rigidbody>().freezeRotation = true; } }
分类:
Unity3D
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码