我有一个可以投掷和拖动的SpriteKit游戏。当它被抛出时,SKCamera会跟随它。我想要的如下图所示:
我怎样才能构建这种障碍?
答案 0 :(得分:2)
一种方法可能是您创建了一个添加SKShapeNode的功能,这是您的障碍。您可以使用阵列保留障碍物列表,其中您可以追踪所有障碍物,并在每次从视野中消失时移除第一个障碍物。这样你的节点数就会保持很低,你可以有无数的障碍。
这是一个示例代码,当玩家在游戏世界中传递最右边的障碍时会产生新的障碍。
private var obstacles = [SKShapeNode]()
private func addObstacle() {
// Create obstacle aka SKShapeNode
let obstacle = SKShapeNode(rectOf: CGSize(width: 50, height: 50))
obstacle.fillColor = SKColor.white
// If this is first obstacle, position it just beyond right side of the view. If not, get rightmost obstacles position and make a little gap between it and new obstacle.
if let lastObstacle = self.obstacles.last {
obstacle.position = CGPoint(x: lastObstacle.frame.maxX + self.frame.width/2, y: 0)
} else {
obstacle.position = CGPoint(x: self.frame.width/2 + obstacle.frame.width, y: 0)
}
// SKShapeNode have physicsbody where you can define categorybitmask etc
obstacle.physicsBody?.categoryBitMask = ...
// Add obstacle to the scene
self.addChild(obstacle)
// Add obstacle to array so we can keep record of those
self.obstacles.append(obstacle)
}
override func update(_ currentTime: TimeInterval) {
// If the rightmost obstacle come visible, create new obstacle
if let lastObstacle = self.obstacles.last {
if lastObstacle.frame.minX < self.camera.frame.maxX {
self.addObstacle()
}
}
// If arrays first obstacle is out of view, remove it from view and array
if (self.obstacles.first?.frame.maxX ?? 0) < self.camera.frame.minX {
self.obstacles.first?.removeFromParent()
self.obstacles.removeFirst()
}
}