I have the following code in my grounded state, which works perfect on its first enter, it can be switched to any other state I want, but after entering in the grounded state for the second time, the player gets stuck in this state. Any idea why would that happen?
using UnityEngine;
public class PlayerGroundedState : PlayerBaseState
{
public PlayerGroundedState(PlayerStateManager currentContext, PlayerStateFactory playerStateFactory)
: base (currentContext, playerStateFactory) {
IsRootState = true;
InitializeSubstate();
}
public override void EnterState() {
Debug.Log("grounded state; landed = " + Ctx.Landed);
Ctx.CurrentMovementY = Ctx.GroundedGravity;
Ctx.AppliedMovementY = Ctx.GroundedGravity;
}
public override void UpdateState() {
CheckSwitchStates();
}
public override void ExitState() {}
public override void CheckSwitchStates() {
if(Ctx.IsJumpPressed && !Ctx.RequireNewJumpPress) {
SwitchState(Factory.Jump());
}
else if(Ctx.IsFalling) {
SwitchState(Factory.Fall());
}
}
public override void InitializeSubstate() {
if(!Ctx.Landed) {
SwitchState(Factory.Land());
}
else if(Ctx.IsMovementPressed) {
SetSubState(Factory.Run());
}
else {
SetSubState(Factory.Idle());
}
}
}
**My abstract class**
public abstract class PlayerBaseState {
private PlayerStateManager _ctx;
private PlayerStateFactory _factory;
private PlayerBaseState _currentSuperState;
private PlayerBaseState _currentSubState;
private bool _isRootState = false;
protected bool IsRootState { set { _isRootState = value; } }
protected PlayerStateManager Ctx { get { return _ctx; } }
protected PlayerStateFactory Factory { get { return _factory; } }
public PlayerBaseState(PlayerStateManager currentContext, PlayerStateFactory playerStateFactory) {
_ctx = currentContext;
_factory = playerStateFactory;
}
public abstract void EnterState();
public abstract void UpdateState();
public abstract void ExitState();
public abstract void CheckSwitchStates();
public abstract void InitializeSubstate();
public void UpdateStates() {
UpdateState();
if (_currentSubState != null) {
_currentSubState.UpdateStates();
}
}
protected void SwitchState(PlayerBaseState newState) {
ExitState();
newState.EnterState();
if(_isRootState) {
_ctx.CurrentState = newState;
} else if (_currentSuperState != null) {
_currentSuperState.SetSubState(newState);
}
}
protected void SetSuperState(PlayerBaseState newSuperState) {
_currentSuperState = newSuperState;
}
protected void SetSubState(PlayerBaseState newSubState) {
_currentSubState = newSubState;
newSubState.SetSuperState(this);
}
}
↧