Unity 视角控制器/人物控制器
帮两个,一个控制水平,一个控制上下
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseLook : MonoBehaviour { //MouseLook.cs //无重力:放在人上MouseXAndY //加重力: 人水平MouseX 摄像机垂直MouseY 原因:P39 public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 } public RotationAxes axes = RotationAxes.MouseXAndY; public float speedV = 9.0f; public float speedH = 9.0f; public float maxhead = 45.0f; public float minhead = -45.0f; private float _rotationX = 0.0f; private float initialV = 0; private float initialH = 0; // Use this for initialization void Start() { Rigidbody body = GetComponent<Rigidbody>(); if (body != null) body.freezeRotation = true;//禁止旋转 } // Update is called once per frame void Update() { if(CommonData.menu.gameObject.activeSelf) { initialV = speedV; initialH = speedH; speedV = 3f; speedH = 3f; } if(CommonData.menu.gameObject.activeSelf==false&& initialV != 0) { speedV = initialV; speedH = initialH; initialV = 0; initialH = 0; } if (CommonData.isTyping==false) { if (axes == RotationAxes.MouseX) { transform.Rotate(0, Input.GetAxis("Mouse X") * speedH, 0); } if (axes == RotationAxes.MouseY) { _rotationX -= Input.GetAxis("Mouse Y") * speedV; _rotationX = Mathf.Clamp(_rotationX, minhead, maxhead);//限仰视俯视角度范围 float _rotationY = transform.localEulerAngles.y; transform.localEulerAngles = new Vector3(_rotationX, _rotationY, 0);//设置旋转角度 } if (axes == RotationAxes.MouseXAndY) { _rotationX -= Input.GetAxis("Mouse Y") * speedV ;//注意是-= _rotationX = Mathf.Clamp(_rotationX, minhead, maxhead);//水平Verital float _rotationY = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * speedH; transform.localEulerAngles = new Vector3(_rotationX, _rotationY, 0); } if(Input.GetKeyDown(KeyCode.PageUp)) { speedH += 1; speedV += 1; if (speedH > 50) speedH = 50; if (speedV > 50) speedV = 50; } if(Input.GetKeyDown(KeyCode.PageDown)) { speedH -= 1; speedV -= 1; if (speedH < 1) speedH = 1; if (speedV < 1) speedV = 1; } } } }