Skip to content

Instantly share code, notes, and snippets.

@orleonedev
Created April 13, 2022 08:23
Show Gist options
  • Save orleonedev/73bb9fcba0099292e747993ae69a591c to your computer and use it in GitHub Desktop.
Save orleonedev/73bb9fcba0099292e747993ae69a591c to your computer and use it in GitHub Desktop.
WillPower Health States in version 0.0.1(3)
class WPHealthState: GKState {
weak var game: WPGame?
var entity: WPEntity
init(withGame: WPGame, entity: WPEntity) {
self.game = withGame
self.entity = entity
super.init()
}
}
class WPDefendState: WPHealthState {
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return stateClass is WPHitState.Type
}
override func didEnter(from previousState: GKState?) {
print("Defend State")
}
}
class WPHitState: WPHealthState {
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return stateClass is WPDefeatedState.Type || stateClass is WPInvulnerableState.Type
}
override func didEnter(from previousState: GKState?) {
print("HitState")
if let component = entity.component(ofType: WPHealthComponent.self) {
if let spriteComponent = entity.component(ofType: WPSpriteComponent.self){
spriteComponent.pulseEffectEnabled = true
spriteComponent.sprite?.colorBlendFactor = 0.8
game?.ignoreContacts = true
}
component.heartCounter -= 1
print("** remaining Heart: \\(component.heartCounter)")
if component.heartCounter <= 0 {
self.stateMachine?.enter(WPDefeatedState.self)
}
else {
self.stateMachine?.enter(WPInvulnerableState.self)
}
}
}
}
class WPInvulnerableState: WPHealthState {
var duration: TimeInterval = 2.0
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return stateClass is WPDefendState.Type
}
override func didEnter(from previousState: GKState?) {
print("invulnerable state")
duration = 2.0
}
override func willExit(to nextState: GKState) {
if let spriteComponent = entity.component(ofType: WPSpriteComponent.self){
spriteComponent.pulseEffectEnabled = false
spriteComponent.sprite?.colorBlendFactor = 0.0
game?.ignoreContacts = false
}
}
override func update(deltaTime seconds: TimeInterval) {
self.duration -= seconds
if self.duration < 0 {
stateMachine?.enter(WPDefendState.self)
}
}
}
class WPDefeatedState: WPHealthState {
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return false
}
override func didEnter(from previousState: GKState?) {
print("Defeated State")
if let spriteComponent = entity.component(ofType: WPSpriteComponent.self){
spriteComponent.pulseEffectEnabled = false
spriteComponent.sprite?.colorBlendFactor = 0.0
spriteComponent.sprite?.run(SKAction.sequence([SKAction.fadeOut(withDuration: 0.5), SKAction.run {
self.game?.LevelStateMachine?.enter(WPGameOverState.self)
}]))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment