4-5 Simplify Unity's ThirdPersonCharacter Class
先來重構ThirdPersonCharacter.cs,由於我們的遊戲中不會使用到跳躍跟墜落狀態,所以原先由ThirdPersonCharacter所提供的相關函式都可以刪除。往後的重構還會將ThirdPersonCharacter刪除,但現階段我們必須先進行簡化後確保遊戲可以正常執行。
大家要記得重構時不要一次改變太多,我們需要先將真正需要的功能挑選出來,後續和其他類別合併時才能順利進行。
先看看目前的ThirdPersonCharacter,有太多不需要的參數了。
以下提供重構後的ThirdPersonCharacter.cs:
Animator內的Jump可以刪除了。
JumpLeg也可以刪除。
目前的ThirdPersonCharacter.cs參數看起來簡單多了吧。
大家要記得重構時不要一次改變太多,我們需要先將真正需要的功能挑選出來,後續和其他類別合併時才能順利進行。
先看看目前的ThirdPersonCharacter,有太多不需要的參數了。
以下提供重構後的ThirdPersonCharacter.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | using UnityEngine; namespace UnityStandardAssets.Characters.ThirdPerson { [RequireComponent( typeof (Rigidbody))] [RequireComponent( typeof (CapsuleCollider))] [RequireComponent( typeof (Animator))] public class ThirdPersonCharacter : MonoBehaviour { [SerializeField] float movingTurnSpeed = 360; [SerializeField] float stationaryTurnSpeed = 180; Rigidbody myRigidbody; Animator animator; float turnAmount; float forwardAmount; void Start() { animator = GetComponent<animator>(); myRigidbody = GetComponent<rigidbody>(); myRigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ; animator.applyRootMotion = true ; } public void Move(Vector3 move) { // convert the world relative moveInput vector into a local-relative // turn amount and forward amount required to head in the desired // direction. if (move.magnitude > 1f) move.Normalize(); move = transform.InverseTransformDirection(move); turnAmount = Mathf.Atan2(move.x, move.z); forwardAmount = move.z; ApplyExtraTurnRotation(); // send input and other state parameters to the animator UpdateAnimator(move); } void UpdateAnimator(Vector3 move) { // update the animator parameters animator.SetFloat( "Forward" , forwardAmount, 0.1f, Time.deltaTime); animator.SetFloat( "Turn" , turnAmount, 0.1f, Time.deltaTime); } void ApplyExtraTurnRotation() { // help the character turn faster (this is in addition to root rotation in the animation) float turnSpeed = Mathf.Lerp(stationaryTurnSpeed, movingTurnSpeed, forwardAmount); transform.Rotate(0, turnAmount * turnSpeed * Time.deltaTime, 0); } } } </rigidbody></animator> |
Animator內的Jump可以刪除了。
JumpLeg也可以刪除。
目前的ThirdPersonCharacter.cs參數看起來簡單多了吧。
留言
張貼留言