GameplayKit的GKStateMachine用法与实例

GKStateMachine

玩家进入GameScene场景中 -> 通过GKStateMachine进入到指定的游戏状态GKState

在GameScene场景中 -> 根据不同的逻辑调用GKStateMachine -> 在各个不同的游戏状态GKState之间进行切换

源码如下:

一、GameScene.swft

import SpriteKit
import GameplayKit

class GameScene: SKScene,SKPhysicsContactDelegate {
    
    //MARK: - StateMachine 场景中各个舞台State
    lazy var stateMachine:GKStateMachine = GKStateMachine(states: [
        WaitingState(scene: self),
        PlayState(scene: self),
        GameOverState(scene: self)])

override func didMove(to view: SKView) {
 stateMachine.enter(MenuState.self) // 进入MenuState
}

   func restartGame(){
        let newScene = GameScene(fileNamed: "GameScene")!
        newScene.size = CGSize(width: SCENE_WIDTH, height: SCENE_HEIGHT)
        newScene.anchorPoint = CGPoint(x: 0, y: 0)
        newScene.scaleMode   = .aspectFill
        let transition = SKTransition.crossFade(withDuration: TimeInterval(0.5))
        view?.presentScene(newScene, transition:transition)
        //reload GameScene 直接进入游戏状态;
        newScene.stateMachine.enter(PlayState.self)
    }

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {
            return
        }
        // 当 physicsWorld.body(at: touchLocation)为nil时
        // 采用atPoint 取得场景中的的精灵
        let touchLocation = touch.location(in: self) ///获得点击的位置
        let nodeAtPoint = self.atPoint(touchLocation) //返回SKNode
        /// 判断目前的GameScene场景舞台是哪个state
        switch stateMachine.currentState {
        case is WaitingState:
            
            /// 判断是否是点击了PlayButton
            if nodeAtPoint.name == "playButton" {
                stateMachine.enter(PlayState.self)
            }
            
            if nodeAtPoint.name == "learnTemp" {
                print("weird")
                UIApplication.shared.open(URL(string: "http://www.iFIERO.com")!, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: { (error) in
                    print("jump to http://www.iFiero.com")
                })
            }
            
        case is PlayState:
            //挑战:判断是否是点击了暂停按钮 PauseButton
            //            if nodeAtPoint.name == "pauseButton" {
            //                stateMachine.enter(PauseState.self)
            //            }
            break;
        case is GameOverState:
            
            if nodeAtPoint.name == "tapToPlay" {
                restartGame()
            }
            
        default:
            break;
        }
    }

  //MARK: - 时时更新
    override func update(_ currentTime: TimeInterval) {
        /// 获取时间差
        if lastUpdateTimeInterval == 0 {
            lastUpdateTimeInterval = currentTime
        }
        dt = currentTime - lastUpdateTimeInterval
        lastUpdateTimeInterval = currentTime
        stateMachine.update(deltaTime: dt)  // 调用所有State内的update方法
    }

}

二、MenuState.swft

//
//  MenuState.swift
//  Copyright © 2018 iFiero. All rights reserved.
//

import SpriteKit
import GameplayKit

class MenuState:GKState {
    
    // 必须引入场景(如:GameScene)
    unowned let scene:GameScene

    // 执行didEnter前,可在init()初始化代码
    init(scene:SKScene){
        self.scene = scene as! GameScene
        super.init()
        print("Menu State")
    }
    // 进入当前状态时触发
    override func didEnter(from previousState: GKState?) {
        
    }
    // 离开当前状态时触发
    override func willExit(to nextState: GKState) {
        
    }
    /* 返回一个布尔值
     * 该值指示当前处于该状态的状态机是否允许转换到指定状态
     * 通俗点讲就是:如果stateMachine(状态机)的状态是PlayState,那么就从MenuState状态转到PlayState状态
    */
    override func isValidNextState(_ stateClass: AnyClass) -> Bool {
        return stateClass is PlayState.Type
    }
    
    // Execute Update Per Frame,游戏运行过程中的每一帧都会执行
    // 但须在GameScene update内调用stateMachine.update()
    override func update(deltaTime seconds: TimeInterval) {
        
    }
}


三、PlayingState.swft

import SpriteKit
import GameplayKit

class PlayState:GKState {
    unowned let scene:GameScene
    
    init(scene:SKScene){
        self.scene = scene as! GameScene
        super.init()
        print("Play State")
    }
    
    override func didEnter(from previousState: GKState?) {
        
    }

    // 挑战:创建游戏暂停GKState状态 PauseState.swift
    // return (stateClass == PauseState.self) || (stateClass == GameOverState.self)
    override func isValidNextState(_ stateClass: AnyClass) -> Bool {
        return stateClass is GameOverState.Type
        
    }
    
    // Excute Update Per Frame
    override func update(deltaTime seconds: TimeInterval) {
        // update 用于判断球的速度是否过快,如果太快了则设置linearDamping的阻力
    }
    
}

四、GameOverState.swft

import SpriteKit
import GameplayKit

class GameOverState:GKState {
    
    unowned let scene:GameScene
    init(scene:SKScene){
        self.scene = scene as! GameScene
        super.init()
    }
    
    override func didEnter(from previousState: GKState?) {
        print("GameOver State 游戏结束")
    }
    
    override func isValidNextState(_ stateClass: AnyClass) -> Bool {
        return stateClass is PlayState.Type
       // return (stateClass == PlayState.self) || (stateClass == MenuState.self)
    }
}

更多游戏教学:http://www.iFIERO.com -- 为游戏开发深感自豪

源码传送门:https://github.com/apiapia/BreakOutGameVansVTutorial

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 177,249评论 25 709
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,573评论 2 59
  • This article is a record of my journey to learn Game Deve...
    蔡子聪阅读 9,422评论 0 9
  • 1. 太阳真的好大,晃得人睁不开眼睛,心都被晒慌了。 立阳今天准备回趟娘家。离家三年来,她一直不敢跟家里联系。她害...
    梨笑阅读 4,565评论 28 26
  • 春来,遍山桃李花开 一瓣一瓣, 开成 开成诱惑的形状 夏至,数池嫩荷出水 一卷一卷, 散发 散发水乡的芬芳 雨霁...
    湘水碧波阅读 1,711评论 2 5

友情链接更多精彩内容