Unity實現(xiàn)人物旋轉和移動效果
更新時間:2020年01月20日 15:47:07 作者:StupidKen
這篇文章主要為大家詳細介紹了Unity實現(xiàn)人物旋轉和移動效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Unity實現(xiàn)人物旋轉和移動的具體代碼,供大家參考,具體內容如下
旋轉
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseLook : MonoBehaviour { public enum RotationAxes { MouseXandY = 0, MouseX = 1, MouseY = 2 } public RotationAxes axes = RotationAxes.MouseXandY; public float sensitivityHor = 9.0f; public float sensitivityVert = 9.0f; public float minVert = -45.0f; public float maxVert = 45.0f; private float _rotationX = 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 () { //水平旋轉就是以Y軸作為旋轉軸旋轉,鼠標移動量為偏移量 if (axes == RotationAxes.MouseX) { transform.Rotate (0, Input.GetAxis("Mouse X") * sensitivityHor, 0);//通過“增加”旋轉角度進行旋轉(X,Y,Z為對應方向的增加量),一般用于無限制旋轉 } else if (axes == RotationAxes.MouseY) { _rotationX -= Input.GetAxis ("Mouse Y") * sensitivityVert; _rotationX = Mathf.Clamp (_rotationX, minVert, maxVert);//限制_rotationX的值在minVert與minVert之間 float rotationY = transform.localEulerAngles.y; //Debug.Log ("rotationX:"+_rotationX+","+Input.GetAxis ("Mouse Y") * sensitivityVert); transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);//直接“設置”旋轉角度進行旋轉,一般用于有限制旋轉 } else { _rotationX -= Input.GetAxis ("Mouse Y") * sensitivityVert; _rotationX = Mathf.Clamp (_rotationX, minVert, maxVert); float delta = Input.GetAxis ("Mouse X") * sensitivityHor; float rotationY = transform.localEulerAngles.y + delta; transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0); } } }
移動
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(CharacterController))]//如果對象沒有該組件,則創(chuàng)建一個 [AddComponentMenu("Control Script/FPS Input")]//可以在Add Component查到 public class FPSInput : MonoBehaviour { private CharacterController _characterController; public float speed = 10.0f; public float gravity = -9.8f; // Use this for initialization void Start () { _characterController = GetComponent<CharacterController>();//獲取對象里的某一組件 } // Update is called once per frame void Update () { float deltaX = Input.GetAxis ("Horizontal") * speed; float deltaZ = Input.GetAxis ("Vertical") * speed; Vector3 movement = new Vector3 (deltaX, 0, deltaZ); movement = Vector3.ClampMagnitude (movement, speed);//保持各方向的速度相同 movement.y = gravity; movement = movement * Time.deltaTime;//向量可以直接乘以一個數(shù),Time.deltaTime確保在每臺計算機上的速度相同 movement = transform.TransformDirection (movement);//將本地坐標轉換為世界坐標 _characterController.Move(movement);//通過CharacterController進行移動而不是transform.Translate } }
問題
人物移動到父容器的邊緣時,人物的移動會產生偏移(甚至飛起來)。將父容器擴大,使人物無法接近邊緣則不會有異常。
父容器比較大
父容器比較小,人物到達邊緣
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
分享WCF文件傳輸實現(xiàn)方法---WCFFileTransfer
這篇文章主要介紹了分享WCF文件傳輸實現(xiàn)方法---WCFFileTransfer,需要的朋友可以參考下2015-11-11