4-5 Simplify Unity's ThirdPersonCharacter Class
先來重構ThirdPersonCharacter.cs,由於我們的遊戲中不會使用到跳躍跟墜落狀態,所以原先由ThirdPersonCharacter所提供的相關函式都可以刪除。往後的重構還會將ThirdPersonCharacter刪除,但現階段我們必須先進行簡化後確保遊戲可以正常執行。
大家要記得重構時不要一次改變太多,我們需要先將真正需要的功能挑選出來,後續和其他類別合併時才能順利進行。
先看看目前的ThirdPersonCharacter,有太多不需要的參數了。
以下提供重構後的ThirdPersonCharacter.cs:
Animator內的Jump可以刪除了。
JumpLeg也可以刪除。
目前的ThirdPersonCharacter.cs參數看起來簡單多了吧。
大家要記得重構時不要一次改變太多,我們需要先將真正需要的功能挑選出來,後續和其他類別合併時才能順利進行。
先看看目前的ThirdPersonCharacter,有太多不需要的參數了。
以下提供重構後的ThirdPersonCharacter.cs:
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();
myRigidbody = GetComponent();
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);
}
}
}
Animator內的Jump可以刪除了。
JumpLeg也可以刪除。
目前的ThirdPersonCharacter.cs參數看起來簡單多了吧。




留言
張貼留言