我想删除屏幕外的所有对象。目前我使用"障碍"
进行接触检测我初始化屏幕周围的障碍,当SpriteNode与其中一个接触时,它将从场景中删除。但是这种方法不能很好地工作并使我的游戏崩溃。
您知道是否有一种简单的方法可以从屏幕上删除所有对象吗?
这里我的代码有障碍:
// declarations
var barrierLeft:SKSpriteNode = SKSpriteNode()
var barrierRight:SKSpriteNode = SKSpriteNode()
var barrierTop:SKSpriteNode = SKSpriteNode()
// In didMoveToView method
barrierLeft.size = CGSizeMake(1, self.frame.height*2)
barrierLeft.physicsBody = SKPhysicsBody (rectangleOfSize: barrierLeft.size)
barrierRight.position = CGPointMake(0, 0)
barrierLeft.physicsBody?.dynamic = false
barrierLeft.physicsBody?.categoryBitMask = barrierCategory
barrierLeft.physicsBody?.contactTestBitMask = flechetteCategory
addChild(barrierLeft)
barrierRight.size = CGSizeMake(1, self.frame.height*2)
barrierRight.physicsBody = SKPhysicsBody (rectangleOfSize: barrierLeft.size)
barrierRight.position = CGPointMake(self.size.width+10, 0)
barrierRight.physicsBody?.dynamic = false
barrierRight.physicsBody?.categoryBitMask = barrierCategory
barrierRight.physicsBody?.contactTestBitMask = flechetteCategory
addChild(barrierRight)
//
func didBeginContact(contact: SKPhysicsContact!)
{
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
{
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else
{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if ((firstBody.categoryBitMask & flechetteCategory) != 0 && (secondBody.categoryBitMask & barrierCategory) != 0)
{
flecheDidCollideWithbarrier(firstBody.node as SKSpriteNode, barrier: secondBody.node as SKSpriteNode)
}
//
func flecheDidCollideWithbarrier (fleche: SKSpriteNode, barrier: SKSpriteNode)
{
println("barrière")
counterGainTime = 0
fleche.removeFromParent()
}
感谢您的帮助!
答案 0 :(得分:6)
您可以检查每个节点的位置,以确定它是否在场景中。然后,您可以相应地删除节点。
override func update(currentTime: CFTimeInterval) {
// Loop over all nodes in the scene
self.enumerateChildNodesWithName("*") {
node, stop in
if (node is SKSpriteNode) {
let sprite = node as SKSpriteNode
// Check if the node is not in the scene
if (sprite.position.x < -sprite.size.width/2.0 || sprite.position.x > self.size.width+sprite.size.width/2.0
|| sprite.position.y < -sprite.size.height/2.0 || sprite.position.y > self.size.height+sprite.size.height/2.0) {
sprite.removeFromParent()
}
}
}
}