轉載請注明出處:🔗https://blog.csdn.net/weixin_44013533/article/details/146409453
作者:CSDN@|Ringleader|
1 結構
1.1 狀態機
1.2 SMB
2 代碼實現
2.1 核心控制
Player_Base_SMB 繼承 StateMachineBehaviour ,控制變量初始化,以及OnStateUpdate每幀控制狀態切換和邏輯處理。
具體 SwitchState
DoStateJob
交由繼承的SMB來實現。
public class Player_Base_SMB : StateMachineBehaviour
{protected static int PLAYER_STATE_IDLE = Animator.StringToHash("Idle");protected static int PLAYER_STATE_RUN = Animator.StringToHash("Run");protected static int PLAYER_STATE_JUMPUP = Animator.StringToHash("JumpUp");protected static int PLAYER_STATE_FALL = Animator.StringToHash("Fall");protected static int PLAYER_STATE_LAND = Animator.StringToHash("Land");// Combat Stateprotected static int PLAYER_COMBAT_IDLE = Animator.StringToHash("Combat_Idle");protected static int PLAYER_COMBAT_BAREHANDS_COMBO1 = Animator.StringToHash("Combat_BareHands_Combo1");protected static int PLAYER_COMBAT_BAREHANDS_COMBO2 = Animator.StringToHash("Combat_BareHands_Combo2");protected static int PLAYER_COMBAT_BAREHANDS_COMBO4 = Animator.StringToHash("Combat_BareHands_Combo4");public string StateName;protected PlayerInput _playerInput;protected PlayerController _playerController;protected Transform _playerTransform;protected Transform _camTransform;protected Rigidbody _playerRig;protected PlayableDirector _playerTimeline;[Tooltip("在project中右鍵添加對應SO,并在狀態機狀態中添加SO,那樣運行時就可在SO中調整參數")]public Player_State_SO playerStateSo;protected bool isOnGround() => _playerController.isOnGround();protected bool AnimationPlayFinished(AnimatorStateInfo stateInfo){return stateInfo.normalizedTime >= 1.0f;}// 只進行一次的初始化private void Initiate(Animator animator){// 如果當前狀態已經初始化過,則跳過Initiateif (_playerInput != null && _playerRig != null){return;}_playerInput = animator.GetComponent<PlayerInput>();_playerController = animator.GetComponent<PlayerController>();_playerTransform = _playerController.transform;_playerRig = animator.GetComponent<Rigidbody>();_camTransform = Camera.main.transform;_playerTimeline = _playerController.playerTimeline;// 注意log用到了PlayerController logEnable之類參數,使用Log方法前要確保依賴類已經初始化LogStateAndMethod(StateName, "StateInitiation");}public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){Initiate(animator);// 注意log用到了PlayerController logEnable之類參數,使用Log方法前要確保依賴類已經初始化LogStateAndMethod(StateName, "OnStateEnter");}public override void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){SwitchState(animator, stateInfo, layerIndex);DoStateJob(animator, stateInfo, layerIndex);}protected virtual void DoStateJob(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){LogStateAndUpdateMethod(StateName, "OnStateUpdate-DoStateJob");}protected virtual void SwitchState(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){LogStateAndUpdateMethod(StateName, "OnStateUpdate-SwitchState");}public override void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){LogStateAndMethod(StateName, "OnStateExit");}protected void DoMoveInPhysics(){if (_playerInput.moveInput != Vector2.zero){Vector3 moveInput = new Vector3(_playerInput.moveInput.x, 0, _playerInput.moveInput.y);// slopeNormal用于計算地面坡度var slopeNormal = _playerController.slopeNormal();// 相對主攝的移動(注意最后需要投影到水平面,否則會有上下位移導致鏡頭波動)Vector3 _camMoveWithSlope = Vector3.ProjectOnPlane(_camTransform.TransformDirection(moveInput).normalized,slopeNormal != Vector3.zero ? slopeNormal : Vector3.up);Vector3 _camMoveWithoutSlope =Vector3.ProjectOnPlane(_camTransform.TransformDirection(moveInput).normalized, Vector3.up);// 轉向_playerRig.MoveRotation(Quaternion.RotateTowards(_playerTransform.rotation,Quaternion.LookRotation(_camMoveWithoutSlope), playerStateSo.rotateSpeed));// 移動_playerRig.MovePosition(_playerRig.position +_camMoveWithSlope * playerStateSo.runSpeed * Time.fixedDeltaTime);}}protected void SetVelocityY(float y){var velocity = _playerRig.linearVelocity;velocity = new Vector3(velocity.x, y, velocity.z);_playerRig.linearVelocity = velocity;}protected void SoundPlayRandom(AudioClip[] clips, float minPitch, float maxPitch, float minVolume, float maxVolume,bool loop = false){if (clips.Length == 0){LogDebug($"請檢查{StateName}狀態的audio音效是否添加");return;}_playerController.PlayRandomSound(clips, minPitch, maxPitch, minVolume, maxVolume, loop);}protected void StopSound(){_playerController.StopSound();}#region Log Methodprotected void LogDebug(string str){if (_playerController.logEnable){Debug.Log(str + " Current frame:" + Time.frameCount);}}protected void LogStateAndMethod(string StateName, string methodName){LogDebug($"Current state: {StateName}, Current method execute : {methodName};\r\n");}protected void LogStateAndUpdateMethod(string StateName, string methodName){if (_playerController.stateUpdateLogEnable){Debug.Log($"Current state: {StateName}, Current method execute : {methodName};\r\n" + " Current frame:" +Time.frameCount);}}#endregion
}
2.2 combat狀態 統一父類+combat狀態入口&出口
出口就是Interrupt
方法,決定何時中斷當前狀態。
父類主要做通用技能中斷,比如被 移動、跳躍、墜落等狀態中斷的情況。
技能銜接如combo之類交由子類SMB控制。
public class SMB_Combat_Base : Player_Base_SMB
{protected float interruptNormalizedTime = 0.8f;//todo 待細化protected bool canInterrup = true;public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.OnStateEnter(animator, stateInfo, layerIndex);// combat 采用 root motion,動作產生位移if (!animator.applyRootMotion){animator.applyRootMotion = true;//必須加,就算有OnStateMove也要開啟。}}protected override void SwitchState(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.SwitchState(animator, stateInfo, layerIndex);Interrupt(animator);}protected void Interrupt(Animator animator){// 如果攻擊正在播放,無法中斷,攻擊收尾階段方可中斷(當然中斷還可以細化,產生優先級,最高優先級甚至可以無視當前出手)if (!canInterrup) return;// any state transform// 1.any combat state → movement state // 1.1 combat to Run(copy from movement Idle的狀態轉換)if (_playerInput.moveInput != Vector2.zero){StopTimeline(_playerTimeline);animator.Play(PLAYER_STATE_RUN);}// 1.2 combat to jumpif (_playerInput.jumpInput){StopTimeline(_playerTimeline);animator.Play(PLAYER_STATE_JUMPUP);}// 1.3 combat to fallif (!isOnGround()){StopTimeline(_playerTimeline);animator.CrossFade(PLAYER_STATE_FALL, playerStateSo.idle_to_fall_duration);}}private void StopTimeline(PlayableDirector timeline){Debug.Log("timeline.duration="+timeline.duration);// timeline.Stop();}
}
2.3 具體狀態SMB
2.3.1 戰斗待機
// 戰斗待機
public class SMB_Combat_Idle : SMB_Combat_Base
{protected override void SwitchState(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.SwitchState(animator, stateInfo, layerIndex);// 攻擊if (_playerInput.fireInput){animator.Play(PLAYER_COMBAT_BAREHANDS_COMBO1);}// 脫離戰斗,這里簡化為戰斗待機播兩次后回答基礎待機(實戰時可能條件很復雜,比如主動收刀、周圍無敵人、未受到傷害等)if (stateInfo.normalizedTime > 1f){animator.Play(PLAYER_STATE_IDLE);}}
}
2.3.2 空手連接1
// 空手連擊1
public class SMB_Combat_Barehands_Combo1 : SMB_Combat_Base
{private Vector3 moveInput;private Vector3 _camMoveWithoutSlope;private Vector3 _camMoveWithSlope;private bool canMoveBeforeAttack = false;public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.OnStateEnter(animator, stateInfo, layerIndex);canInterrup = false;}private void StopTimeline(PlayableDirector timeline,string reason){Debug.Log("for reason:"+reason+",timeline.duration="+timeline.duration);timeline.Stop();}protected override void SwitchState(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.SwitchState(animator, stateInfo, layerIndex);if (animator.IsInTransition(layerIndex)){return;}// 播放結束回到戰斗待機狀態if (stateInfo.normalizedTime >= 1f){StopTimeline(_playerTimeline,"播放結束回到戰斗待機狀態");animator.Play(PLAYER_COMBAT_IDLE);}else if (stateInfo.normalizedTime >= 0.4f){// 慢擊if (_playerInput.fireInput){StopTimeline(_playerTimeline,"慢擊");animator.Play(PLAYER_COMBAT_BAREHANDS_COMBO1,layerIndex,0f);}}else if (stateInfo.normalizedTime is > 0.3f and < 0.4f){// 連擊if (_playerInput.fireInput){StopTimeline(_playerTimeline,"連擊");animator.CrossFade(PLAYER_COMBAT_BAREHANDS_COMBO2,0.1f);}}// 前搖時接收最后的轉向if (stateInfo.normalizedTime <= 0.2f){if (_playerInput.moveInput != Vector2.zero){canMoveBeforeAttack = true;moveInput = new Vector3(_playerInput.moveInput.x, 0, _playerInput.moveInput.y);// slopeNormal用于計算地面坡度var slopeNormal = _playerController.slopeNormal();// 相對主攝的移動(注意最后需要投影到水平面,否則會有上下位移導致鏡頭波動)_camMoveWithSlope = Vector3.ProjectOnPlane(_camTransform.TransformDirection(moveInput).normalized,slopeNormal != Vector3.zero ? slopeNormal : Vector3.up);_camMoveWithoutSlope =Vector3.ProjectOnPlane(_camTransform.TransformDirection(moveInput).normalized, Vector3.up);}}// 設定攻擊打斷條件,一般與連招斷續窗口一致,即攻擊打實后準備收招那一刻(后搖開始時)if (stateInfo.normalizedTime >= 0.4f){canInterrup = true;}}// 執行轉向和移動public override void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.OnStateMove(animator, stateInfo, layerIndex);// animator.bodyPosition += animator.deltaPosition;//有問題,沒有成功執行// _playerRig.linearVelocity = animator.velocity;//移動跳躍異常,轉向正常_playerRig.MovePosition(_playerRig.position+animator.deltaPosition);//完美!if (canMoveBeforeAttack && stateInfo.normalizedTime > 0.2f){canMoveBeforeAttack = false;// 轉向_playerRig.MoveRotation(Quaternion.LookRotation(_camMoveWithSlope));// 移動(可以添加索敵吸附功能)_playerRig.MovePosition(_playerRig.position + _camMoveWithSlope * 5);}}
}
2.3.3 空手連擊2
// 空手連擊2
public class SMB_Combat_Barehands_Combo2 : SMB_Combat_Base
{private Vector3 moveInput;private Vector3 _camMoveWithoutSlope;private Vector3 _camMoveWithSlope;private bool canMoveBeforeAttack = false;public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.OnStateEnter(animator, stateInfo, layerIndex);canInterrup = false;}protected override void SwitchState(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.SwitchState(animator, stateInfo, layerIndex);if (animator.IsInTransition(layerIndex)){return;}// 播放結束回到戰斗待機狀態if (stateInfo.normalizedTime >= 1f){animator.Play(PLAYER_COMBAT_IDLE);}else if (stateInfo.normalizedTime >= 0.3f){// 慢擊if (_playerInput.fireInput){animator.Play(PLAYER_COMBAT_BAREHANDS_COMBO1);}}else if (stateInfo.normalizedTime is > 0.2f and < 0.3f){// 連擊if (_playerInput.fireInput){animator.CrossFade(PLAYER_COMBAT_BAREHANDS_COMBO4,0.1f);}}// 前搖時接收最后的轉向if (stateInfo.normalizedTime <= 0.1f){if (_playerInput.moveInput != Vector2.zero){canMoveBeforeAttack = true;moveInput = new Vector3(_playerInput.moveInput.x, 0, _playerInput.moveInput.y);// slopeNormal用于計算地面坡度var slopeNormal = _playerController.slopeNormal();// 相對主攝的移動(注意最后需要投影到水平面,否則會有上下位移導致鏡頭波動)_camMoveWithSlope = Vector3.ProjectOnPlane(_camTransform.TransformDirection(moveInput).normalized,slopeNormal != Vector3.zero ? slopeNormal : Vector3.up);_camMoveWithoutSlope =Vector3.ProjectOnPlane(_camTransform.TransformDirection(moveInput).normalized, Vector3.up);}}// 設定攻擊打斷條件,一般與連招斷續窗口一致,即攻擊打實后準備收招那一刻(后搖開始時)if (stateInfo.normalizedTime >= 0.3f){canInterrup = true;}}// 執行轉向和移動public override void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.OnStateMove(animator, stateInfo, layerIndex);// animator.bodyPosition += animator.deltaPosition;//有問題,沒有成功執行// _playerRig.linearVelocity = animator.velocity;//移動跳躍異常,轉向正常_playerRig.MovePosition(_playerRig.position+animator.deltaPosition);//完美!if (canMoveBeforeAttack && stateInfo.normalizedTime > 0.1f){canMoveBeforeAttack = false;// 轉向_playerRig.MoveRotation(Quaternion.LookRotation(_camMoveWithSlope));}}
}
2.3.4 空手連擊3
(我取的動畫是combo4)
// 空手連擊4
public class SMB_Combat_Barehands_Combo4 : SMB_Combat_Base
{private Vector3 moveInput;private Vector3 _camMoveWithoutSlope;private Vector3 _camMoveWithSlope;private bool canMoveBeforeAttack = false;public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.OnStateEnter(animator, stateInfo, layerIndex);canInterrup = false;}protected override void SwitchState(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.SwitchState(animator, stateInfo, layerIndex);// 播放結束回到戰斗待機狀態if (stateInfo.normalizedTime >= 1f){animator.Play(PLAYER_COMBAT_IDLE);}else if (stateInfo.normalizedTime >= 0.4f){// 慢擊if (_playerInput.fireInput){animator.Play(PLAYER_COMBAT_BAREHANDS_COMBO1);}}// 前搖時接收最后的轉向if (stateInfo.normalizedTime <= 0.2f){if (_playerInput.moveInput != Vector2.zero){canMoveBeforeAttack = true;moveInput = new Vector3(_playerInput.moveInput.x, 0, _playerInput.moveInput.y);// slopeNormal用于計算地面坡度var slopeNormal = _playerController.slopeNormal();// 相對主攝的移動(注意最后需要投影到水平面,否則會有上下位移導致鏡頭波動)_camMoveWithSlope = Vector3.ProjectOnPlane(_camTransform.TransformDirection(moveInput).normalized,slopeNormal != Vector3.zero ? slopeNormal : Vector3.up);_camMoveWithoutSlope =Vector3.ProjectOnPlane(_camTransform.TransformDirection(moveInput).normalized, Vector3.up);}}// 設定攻擊打斷條件,一般與連招斷續窗口一致,即攻擊打實后準備收招那一刻(后搖開始時)if (stateInfo.normalizedTime >= 0.4f){canInterrup = true;}}// 執行轉向和移動public override void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.OnStateMove(animator, stateInfo, layerIndex);// animator.bodyPosition += animator.deltaPosition;//有問題,沒有成功執行// _playerRig.linearVelocity = animator.velocity;//移動跳躍異常,轉向正常_playerRig.MovePosition(_playerRig.position+animator.deltaPosition);//完美!if (canMoveBeforeAttack && stateInfo.normalizedTime > 0.2f){canMoveBeforeAttack = false;// 轉向_playerRig.MoveRotation(Quaternion.LookRotation(_camMoveWithSlope));}}
}
2.4 從移動向戰斗狀態的切換
這里省略了移動相關SMB,這里只取移動的基類,控制 any movement state → 攻擊
// 移動狀態基類,主要用于anystate轉換
public class SMB_Movement_Base : Player_Base_SMB
{public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.OnStateEnter(animator, stateInfo, layerIndex);// movement 不采用 root motion,由開發者控制位移if (animator.applyRootMotion){animator.applyRootMotion = false;}}protected override void SwitchState(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){base.SwitchState(animator, stateInfo, layerIndex);// any state transform// any movement state → 攻擊if (_playerInput.fireInput){animator.Play(PLAYER_COMBAT_BAREHANDS_COMBO1);}}
}
3 最終效果展示
4 遇到的問題及解決
4.1 角色原地攻擊、攻擊完畢后瞬移
添加連擊狀態后,發現角色只能原地運動。
于是可以考慮將攻擊動畫的RootTransform Position xz 分量 bake into pose,但會發現角色攻擊完畢后會瞬移回模型原點。
在我第十一篇文章《動畫基礎》7.6.2 節中曾詳細比較了humanoid動畫 root motion和bake into pose的情況:
從上面可以知道,要想模型父節點跟隨模型必須應用 root motion
而基礎移動(movement
)又需要交給程序精確控制,如果不使用OnAnimatorMove()
(rootMotion handle by script),可以這樣分開處理:
- 在進入
movement
的狀態,animator.applyRootMotion = false;
; - 進入
combat
的狀態,animator.applyRootMotion = true;
;
這樣攻擊就能正常位移了(注意攻擊動畫的RootTransform Position xz 分量不要 bake into pose)
4.2 連擊動畫父節點瞬移
但如果做連擊動畫
會發現第二、三段攻擊父節點發生位移。
原因就是原動畫第二三段模型就是偏離模型空間原點。
解決辦法就是將動畫的RootTransform Position xz 選擇based upon Center of Mass
。
最終效果:
4.3 同時移動和攻擊會產生鬼畜
anystate transform的問題,移動時攻擊就會瞬間高速循環切換狀態:移動→combat→移動
move combat狀態瞬時切換??
解決方法就是讓攻擊動畫不能無條件隨時打斷,至少播放到40%才能打斷(技能打斷會開新專題)
protected bool canInterrup = true;OnStateEnter(){...canInterrup = false;...
}switchState(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){...if (stateInfo.normalizedTime >= 0.4f){// 攻擊產生后搖后方可打斷canInterrup = true;}if (canInterrup) {// movement 相關輸入判斷}...
}
4.4 狀態無法自轉移(無法重播當前動畫)
假設有攻擊1、攻擊2、攻擊3,這三段連續的攻擊動畫,當播放到20%~40%按下攻擊,便可觸發連擊,40%后再按攻擊鍵便回到攻擊1播放。
現在的問題是,animator.Play(“stateName”) 的狀態是自身的話,也就是慢速連按攻擊鍵,攻擊1動畫無法再次觸發,狀態也沒有切換(exit state 然后再enter state)。
if (stateInfo.normalizedTime >= 0.4f){// 慢擊if (_playerInput.fireInput){animator.Play(PLAYER_COMBAT_BAREHANDS_COMBO1);}}
可能是animator.Play
方法優化的原因,不指定方法的normalizedTime
參數,當前stateName
與待播放的stateName
相同,則不觸發狀態切換。
解決方法就是指定normalizedTime
參數。
animator.Play(PLAYER_COMBAT_BAREHANDS_COMBO1,layerIndex,normalizedTime: 0f);
4.5 連擊切換死板,加過渡后產生鬼畜
如果連擊動畫交接處差異過大,會明顯感覺到跳切,于是可以考慮加上過渡
animator.CrossFade(PLAYER_COMBAT_BAREHANDS_COMBO4,0.1f);
但快速連點攻擊時,會發現鬼畜/慢動作,原因在于,過渡過程兩個狀態的update其實都是進行中的,過渡過程如果也按下攻擊,便會反復觸發這個轉換過程,便是鬼畜。
需要在前者狀態切換添加過濾
SwitchState(Animator animator, AnimatorStateInfo stateInfo, int layerIndex){...if (animator.IsInTransition(layerIndex)){return;}...
}
這一點在我 【Unity實戰筆記】第二十二 跳躍到fall有突然前移現象 小節有提到
5 總結
本文使用SMB+Animator 實現了基礎戰斗系統,但可以看到技能銜接是通過 stateInfo.normalizedTime
判斷的,這種方式不夠完美:
- 第一,基于時間的控制不夠準確,調整起來也很麻煩
- 第二,當需要中斷的條件變多變復雜時,這種if else判斷出現bug的可能會越來越大
- 第三,如果要添加匹配音效、特效,以及更復雜的需求,這種技能編輯方式就捉襟見肘了
所以我希望有一種更直觀的方式去編輯技能,且基于幀的控制,除了能編輯動畫,還能配置音效、粒子特效等。
這就是Timeline!
下一篇見~