iOS 2D游戏开发学习笔记:GameplayKit
这是我的 iOS 2D 游戏开发学习笔记,本篇学习内容来自raywenderlich的GameplayKit Tutorial: Entity-Component System, Agents, Goals, and Behaviors
Entity-Component System 个体-模块系统
可以理解为模块化设计,根据实体的功能需求,运用不同的组件进行组装。区别于 spritekit 中 node 的父子继承关系,运用 GameplayKit 中提供的 GKComponent 和 GKEntity 来进行组件的复用,实现每个实体的个性化功能需求。
GKEntity类初始化
下面代码生成一个游戏怪物 GKEntity 类,运用 spriteComponent、 TeamComponent、MoveComponent 三个组件进行组装,在组件的初始化方法上加上条件满足个性化实体的实现。
class Quirk: GKEntity {
init(team: Team, entityManager: EntityManager) {
super.init()
let texture = SKTexture(imageNamed: "quirk\(team.rawValue)")
let spriteComponent = SpriteComponent(texture: texture)
addComponent(spriteComponent)
addComponent(TeamComponent(team: team))
addComponent(MoveComponent(maxSpeed: 150, maxAcceleration: 5, radius: Float(texture.size().width * 0.3), entityManager: entityManager))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
sprite组件
entity并不等于sprite,entity可以通过定制sprite组件的方式来追踪sprite,以下的组件类初始化了一个 SpriteNode 属性可以让entity“显示”在scene上
class SpriteComponent: GKComponent {
let node: SKSpriteNode
init(texture: SKTexture) {
node = SKSpriteNode(texture: texture, color: SKColor.white, size: texture.size())
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
EntityManager 实体管理类
这个类创建了一个实体集合,并且负责管理实体的生成、去除以及相关的方法
class EntityManager {
// 创建了一个无序的集合类型Set<>
var entities = Set()
let scene: SKScene
init(scene: SKScene) {
self.scene = scene
func add(entity: GKEntity) {
entities.insert(entity)
if let spriteNode = entity.componentForClass(SpriteComponent.self)?.node {
scene.addChild(spriteNode)
}
}
func remove(entity: GKEntity) {
if let spriteNode = entity.componentForClass(SpriteComponent.self)?.node {
spriteNode.removeFromParent()
}
entities.remove(entity)
}
}
update(deltaTime seconds: TimeInterval)
组件中的update方法,与SpriteKit中的update方法类似。但是需要手动调用,直接调用或者通过GKComponentSystem 对象来进行调用。注意参数是时间增量。
override func update(deltaTime seconds: TimeInterval) {
super.update(deltaTime: seconds)
let coinDropInterval = TimeInterval(0.5)
let coinsPerInterval = 10
if (CACurrentMediaTime() - lastCoinDrop > coinDropInterval) {
lastCoinDrop = CACurrentMediaTime()
coins += coinsPerInterval
}
// 金币的生成间隔定为0.5秒,每次生成10枚。
生成 componentSystems 实例
componentSystems 负责管理相同类的组建,集中调用其中组件的update方法
lazy var componentSystems: [GKComponentSystem] = {
let castleSystem = GKComponentSystem(componentClass: CastleComponent.self)
let moveSystem = GKComponentSystem(componentClass: MoveComponent.self)
return [castleSystem, moveSystem]
}()
集中调用组件系统其中组件的update方法,并且负责系统中多余的组件(可以直接移除,但是组件处于被在update方法中被重复引用的情况下会出错)
func update(_ deltaTime: CFTimeInterval) {
for componentSystem in componentSystems {
componentSystem.update(deltaTime: deltaTime)
}
for curRemove in toRemove {
for componentSystem in componentSystems {
componentSystem.removeComponent(foundIn: curRemove)
}
}
toRemove.removeAll()
查找指定的team中含有的castle
这样做的好处是更加灵活,也展示了 entity-component system architecture 的优点。
func castleForTeam(team: Team) -> GKEntity? {
for entity in entities {
// 在if语句条件中验证实体是否含有team组建和castle组件
if let teamComponent = entity.componentForClass(TeamComponent.self),
_ = entity.componentForClass(CastleComponent.self) {
if teamComponent.team == team {
return entity
}
}
}
return nil
}
在指定范围生成怪兽个体
func spawnQuirk(team: Team) {
// 查找队伍的城堡组件和sprite组件(城堡组件用于金币的管理,sprite组件用于城堡位置的读取)
guard let teamEntity = castleForTeam(team),
teamCastleComponent = teamEntity.componentForClass(CastleComponent.self),
teamSpriteComponent = teamEntity.componentForClass(SpriteComponent.self) else {
return
}
// 查询金币数量是否足够
if teamCastleComponent.coins < costQuirk {
return
}
teamCastleComponent.coins -= costQuirk
scene.runAction(SoundManager.sharedInstance.soundSpawn)
// 生成怪兽实例,并处理其生成位置
let monster = Quirk(team: team)
if let spriteComponent = monster.componentForClass(SpriteComponent.self) {
spriteComponent.node.position = CGPoint(x: teamSpriteComponent.node.position.x, y: CGFloat.random(min: scene.size.height * 0.25, max: scene.size.height * 0.75))
spriteComponent.node.zPosition = 2
}
add(monster)
}
Agents, Goals, and Behaviors
代理、目标、行为
- GKAgent2D用于掌控个体的最大速度、加速度等属性供GKBehavior使用
- ** GKBehavior**包含了一系列的GKgoal,代表了个体的行为方式
- GKGoal 设置了个体的行为目标
GKBehavior
初始化行为的目标速度、移动目标、躲避目标
用setWeight() 来设置目标的比重
// 1
class MoveBehavior: GKBehavior {
init(targetSpeed: Float, seek: GKAgent, avoid: [GKAgent]) {
super.init()
// 2
if targetSpeed > 0 {
// 3
setWeight(0.1, forGoal: GKGoal(toReachTargetSpeed: targetSpeed))
// 4
setWeight(0.5, forGoal: GKGoal(toSeekAgent: seek))
// 5
setWeight(1.0, forGoal: GKGoal(toAvoidAgents: avoid, maxPredictionTime: 1.0))
}
}
}
GKAgent2D与GKAgentDelegate
GKAgentDelegate中代理执行agentWillUpdate(agent: GKAgent)和 agentDidUpdate(agent: GKAgent)
其中gentWillUpdate(agent: GKAgent)中的agent的position用于最近敌人的计算,agentDidUpdate(agent: GKAgent)中agent的position用于更新sprite位置
// 1
class MoveComponent : GKAgent2D, GKAgentDelegate {
let entityManager: EntityManager
// 初始化行为代理的属性
init(maxSpeed: Float, maxAcceleration: Float, radius: Float, entityManager: EntityManager) {
self.entityManager = entityManager
super.init()
delegate = self
self.maxSpeed = maxSpeed
self.maxAcceleration = maxAcceleration
self.radius = radius
print(self.mass)
self.mass = 0.01
}
// 执行代理方法
func agentWillUpdate(agent: GKAgent) {
guard let spriteComponent = entity?.componentForClass(SpriteComponent.self) else {
return
}
position = float2(spriteComponent.node.position)
}
// 5
func agentDidUpdate(agent: GKAgent) {
guard let spriteComponent = entity?.componentForClass(SpriteComponent.self) else {
return
}
spriteComponent.node.position = CGPoint(position)
}
}
GKAgent2D中的更新
用于更新agent的行为
override func updateWithDeltaTime(seconds: NSTimeInterval) {
super.updateWithDeltaTime(seconds)
// 1
guard let entity = entity,
let teamComponent = entity.componentForClass(TeamComponent.self) else {
return
}
// 2
guard let enemyMoveComponent = closestMoveComponentForTeam(teamComponent.team.oppositeTeam()) else {
return
}
// 3
let alliedMoveComponents = entityManager.moveComponentsForTeam(teamComponent.team)
// 4
behavior = MoveBehavior(targetSpeed: maxSpeed, seek: enemyMoveComponent, avoid: alliedMoveComponents)
}