C#控制WASD鍵盤控制前后左右+空格鍵抬升高度、鼠標右鍵跟隨旋轉、滑輪控制放大縮小:
using UnityEngine; using System.Collections; public class CameraControl : MonoBehaviour { // Use this for initialization private GameObject gameObject; /** * 鼠標 */ public bool mouseControlEvent = false;//判斷奇數偶數單(右)擊 //模型跟隨鼠標旋轉改變的坐標 public float h; public float v; 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)); } /* * 鼠標按鍵操作 */ //右鍵第一次按下為開啟鼠標跟隨旋轉,第二次按下關閉鼠標跟隨旋轉 if (Input.GetMouseButtonDown(1)) { Debug.Log("鼠標右鍵按下"); if (!mouseControlEvent) { mouseControlEvent = true; } else { mouseControlEvent = false; } } //模型跟隨鼠標旋轉 if (mouseControlEvent) { h = Input.GetAxis("Mouse X"); v = Input.GetAxis("Mouse Y"); transform.Rotate(v,h,0); } /* * 通過鼠標滑輪控制放大縮小 */ //放大視角 往前滑 if (Input.GetAxis("Mouse ScrollWheel")<0) { Debug.Log("放大視角 往前滑"); if (Camera.main.fieldOfView <= 100)//小於一個放大范圍后就不繼續放大了 { Camera.main.fieldOfView += 5; } } //縮小視角 往后滑 if (Input.GetAxis("Mouse ScrollWheel") > 0) { Debug.Log("縮小視角 往后滑"); if (Camera.main.fieldOfView >= 10) { Camera.main.fieldOfView -= 5; } } }
參考文章:https://blog.csdn.net/lisenyang/article/details/48462803