Unity3D 相机控制代码


最常用的方向控制:

上下左右:W/S/A/D

升降:空格/E/Q

加速:按住Shift

代码:

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

public class CameraScript : MonoBehaviour
{
    private float speed = 0.02f;
    private float m_deltX = 0;
    private float m_deltY = 0;
    private float m_mSpeed = 5f;
    private Vector3 V3_Default = new Vector3(0, 0, -10);
    private Vector3 V3_chushi;
    public Vector3 V3_dongtai;
    public Vector3 V3_final;
    public bool diyici = true;

    // Start is called before the first frame update
    void Start()
    {

    }


    // Update is called once per frame
    void Update()
    {
        if (diyici)
        {
            V3_chushi = transform.eulerAngles;
        }

        //鼠标右键控制旋转
        if (Input.GetMouseButton(1))
        {
            diyici = false;
            m_deltX += Input.GetAxis("Mouse X") * m_mSpeed / 2;
            m_deltY -= Input.GetAxis("Mouse Y") * m_mSpeed / 2;
            V3_dongtai = new Vector3(m_deltY, m_deltX, 0);
            V3_final = V3_chushi + V3_dongtai;
            transform.rotation = Quaternion.Euler(V3_final);

        }
        if (Input.GetMouseButtonUp(1))
        {
            diyici = true;
            m_deltX = 0;
            m_deltY = 0;
        }

        //键盘控制移动
        if (Input.GetKey(KeyCode.A))
        {
            transform.Translate(Vector3.left * speed, Space.Self);
        }
        if (Input.GetKey(KeyCode.D))
        {
            transform.Translate(Vector3.right * speed, Space.Self);
        }
        if (Input.GetKey(KeyCode.W))
        {
            transform.Translate(Vector3.forward * speed, Space.Self);
        }
        if (Input.GetKey(KeyCode.S))
        {
            transform.Translate(Vector3.back * speed, Space.Self);
        }
        if (Input.GetKey(KeyCode.Space) || Input.GetKey(KeyCode.Q))
        {
            transform.Translate(Vector3.up * speed, Space.Self);
        }
        if (Input.GetKey(KeyCode.E))
        {
            transform.Translate(Vector3.down * speed, Space.Self);
        }
        if (Input.GetKey(KeyCode.LeftShift))
        {
            speed = 0.2f;
        }
        if (Input.GetKeyUp(KeyCode.LeftShift))
        {
            speed = 0.02f;
        }
    }
}

你可能感兴趣的:(Unity3D,unity3d)