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

 

posted @ 2019-09-28 10:01  一叶之灵  阅读(2206)  评论(0编辑  收藏  举报