我正在尝试使用类似于此处描述的实体组件架构构建一个简单的 iOS 游戏。
我想在我的游戏中实现的是当用户触摸屏幕时,检测触摸发生的位置并将一种类型的所有实体移向特定方向(方向取决于用户触摸的位置,屏幕右侧 = 向上,左侧屏幕 = 向下)。
到目前为止,游戏真的很简单,我才刚刚开始,但我被这个简单的功能困住了:
我的问题是 anSKAction
应该在一种类型的所有实体上运行,但根本不会发生。
在我将游戏重新设计为 ECS 方法之前,它运行良好。
这是GKEntity
我在 Lines.swift 中声明的子类:
class Lines: GKEntity {
override init() {
super.init()
let LineSprite = SpriteComponent(color: UIColor.white, size: CGSize(width: 10.0, height: 300))
addComponent(LineSprite)
// Set physics body
if let sprite = component(ofType: SpriteComponent.self)?.node {
sprite.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: sprite.size.width, height: sprite.size.height))
sprite.physicsBody?.isDynamic = false
sprite.physicsBody?.restitution = 1.0
sprite.physicsBody?.friction = 0.0
sprite.physicsBody?.linearDamping = 0.0
sprite.physicsBody?.angularDamping = 0.0
sprite.physicsBody?.mass = 0.00
sprite.physicsBody?.affectedByGravity = false
sprite.physicsBody?.usesPreciseCollisionDetection = true
sprite.physicsBody?.categoryBitMask = 0b1
sprite.zPosition = 10
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
在TouchesBegan
我调用Move(XAxisPoint: t.location(in: self))
声明的函数时,GameScene
这是什么Move()
:
///Determines direction of movement based on touch location, calls MoveUpOrDown for movement
func move(XAxisPoint: CGPoint){
let Direction: SKAction
let Key: String
if XAxisPoint.x >= 0 {
Direction = SKAction.moveBy(x: 0, y: 3, duration: 0.01)
Key = "MovingUp"
} else {
Direction = SKAction.moveBy(x: 0, y: -3, duration: 0.01)
Key = "MovingDown"
}
moveUpOrDown(ActionDirection: Direction, ActionKey: Key)
}
///Moves sprite on touch
func moveUpOrDown(ActionDirection: SKAction, ActionKey: String) {
let Line = Lines()
if let sprite = Line.component(ofType: SpriteComponent.self)?.node {
if sprite.action(forKey: ActionKey) == nil {
stopMoving()
let repeatAction = SKAction.repeatForever(ActionDirection)
sprite.run(repeatAction, withKey: ActionKey)
}
}
}
///Stops movement
func stopMoving() {
let Line = Lines()
if let sprite = Line.component(ofType: SpriteComponent.self)?.node {
sprite.removeAllActions()
}
}
我猜这行代码有一些问题,Line.component(ofType: SpriteComponent.self)?.node
但是编译器没有抛出任何错误,我不确定我的错误在哪里。
任何帮助/指导将不胜感激!