Unity3D(五)在U3D中添加鼠標控制、鍵盤操作


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM