我正在使用GKAgents,GKGoals和GKBehaviours,但是我的行为和组件之间的内存泄漏了。我认为图像和代码可以更好地解释我的问题:
在我的实体经理中,我返回所有无人机实体:
func droneEntities() -> [GKAgent2D] {
for componentSystem in componentSystems {
if componentSystem.componentClass is DroneMoveComponent.Type {
let components = componentSystem.components
return components.flatMap{ component in
return component as? GKAgent2D
}
}
}
return []
}
我的Dronemove组件:
import SpriteKit
import GameplayKit
class DroneMoveComponent: GKAgent2D, GKAgentDelegate {
weak var entityManager: EntityManager?
init(entityManager: EntityManager) {
self.entityManager = entityManager
super.init()
delegate = self
self.maxSpeed = 50.0
self.mass = 0.01
self.radius = 16
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func agentWillUpdate(_ agent: GKAgent) {
guard let spriteComponent = entity?.component(ofType: SpriteComponent.self) else {
return
}
position = vector_float2(Float(spriteComponent.node.position.x), Float(spriteComponent.node.position.y))
}
func agentDidUpdate(_ agent: GKAgent) {
guard let spriteComponent = entity?.component(ofType: SpriteComponent.self) else {
return
}
spriteComponent.node.position = CGPoint(x: CGFloat(position.x), y: CGFloat(position.y))
}
override func update(deltaTime seconds: TimeInterval) {
super.update(deltaTime: seconds)
if let controlledComponent = entityManager?.playerEntity?.component(ofType: ControlledComponent.self) {
let droneEntities = entityManager?.droneEntities().filter{$0 != self}
behavior = DroneMoveBehaviour(seek: controlledComponent, avoid: (entityManager?.berkEntities())!, drones: droneEntities!)
}
}
}
我的DroneMove行为:
import GameplayKit
import SpriteKit
class DroneMoveBehaviour: GKBehavior {
init(seek: GKAgent, avoid: [GKAgent], drones: [GKAgent]) {
super.init()
setWeight(500, for: GKGoal(toReachTargetSpeed: 50))
setWeight(100, for: GKGoal(toInterceptAgent: seek, maxPredictionTime: 10))
setWeight(1000, for: GKGoal(toAvoid: avoid, maxPredictionTime: 10))
setWeight(1000, for: GKGoal(toAvoid: drones, maxPredictionTime: 10))
}
}
这是我的内存图的图像:
我以相同的方式泄漏了另一组组件和行为,我发现如果有人可以帮助我了解如何解决此问题,我可以自己继续进行纠正。
数组应该包含弱引用吗?我应该切换到NSPointerArray吗?还是我忽略了其他东西?谢谢您在这里的任何指导。
最佳答案
无需在每次更新时都设置DroneMoveComponents行为!在构造函数中仅移动一次此集似乎可以防止泄漏。
关于swift - 如何在GameKit游戏中避免这些循环引用?我正在使用GKAgents2D和GKBehaviours,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49899421/