1. 程式人生 > >Unity 鍵盤WASD 實現物體移動

Unity 鍵盤WASD 實現物體移動

1首先在場景中建立一個Capsule,將主攝像機拖到其物體下。


2.將指令碼掛在Capsule物體下,WASD 控制移動方向,空格延Y軸向上移動,F延Y軸向下移動

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveCam : MonoBehaviour
{
    private Vector3 m_camRot;
    private Transform m_camTransform;//攝像機Transform
    private Transform m_transform;//攝像機父物體Transform
    public float m_movSpeed=10;//移動係數
    public float m_rotateSpeed=1;//旋轉系數
    private void Start()
    {
        m_camTransform = Camera.main.transform;
        m_transform = GetComponent<Transform>();
    }
    private void Update()
    {
        Control();
    }
    void Control()
    {
        if (Input.GetMouseButton(0))
        {
            //獲取滑鼠移動距離
            float rh = Input.GetAxis("Mouse X");
            float rv = Input.GetAxis("Mouse Y");

            // 旋轉攝像機
            m_camRot.x -= rv * m_rotateSpeed;
            m_camRot.y += rh*m_rotateSpeed;

        }

        m_camTransform.eulerAngles = m_camRot;

        // 使主角的面向方向與攝像機一致
        Vector3 camrot = m_camTransform.eulerAngles;
        camrot.x = 0; camrot.z = 0;
        m_transform.eulerAngles = camrot;

        // 定義3個值控制移動
        float xm = 0, ym = 0, zm = 0;

        //按鍵盤W向上移動
        if (Input.GetKey(KeyCode.W))
        {
            zm += m_movSpeed * Time.deltaTime;
        }
        else if (Input.GetKey(KeyCode.S))//按鍵盤S向下移動
        {
            zm -= m_movSpeed * Time.deltaTime;
        }

        if (Input.GetKey(KeyCode.A))//按鍵盤A向左移動
        {
            xm -= m_movSpeed * Time.deltaTime;
        }
        else if (Input.GetKey(KeyCode.D))//按鍵盤D向右移動
        {
            xm += m_movSpeed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.Space) && m_transform.position.y <= 3)
        {
            ym+=m_movSpeed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.F) && m_transform.position.y >= 1)
        {
            ym -= m_movSpeed * Time.deltaTime;
        }
        m_transform.Translate(new Vector3(xm,ym,zm),Space.Self);
    }
}