我正在尝试创建一个SpriteKit游戏,其中一个球在屏幕上移动。当球离开屏幕时,我想将其从父节目中移除并切换到另一个场景(GameOverScene)。
我正在使用enumerateChildNodes
,但它并不像是在运作。我不确定问题是什么,但我认为它可能与父母/子女关系有关...
func createBall(forTrack track: Int) {
setupTracks()
player?.physicsBody?.linearDamping = 0
player = SKSpriteNode(imageNamed: "small")
player?.name = "BALL"
player?.size = CGSize(width: 100, height: 100)
ballValue = 1
randFloat = Float(arc4random()) / Float(UINT32_MAX)
if randFloat > 0.001 {
ballSpeed = randFloat / 50
}
else {
ballSpeed = randFloat / 50
}
let ballPosition = trackArray?[track].position
player?.position = CGPoint(x: (ballPosition?.x)!, y: (ballPosition?.y)!)
player?.position.y = (ballPosition?.y)!
if ballDirection == "right" {
player?.position.x = 0
moveRight()
}
else {
player?.position.x = (self.view?.frame.size.height)!
moveLeft(speed: ballSpeed)
}
self.addChild(player!)
self.enumerateChildNodes(withName: "BALL") { (node: SKNode, nil) in
if node.position.x < -100 || node.position.x > (self.size.width) + 100 {
print("balls Out")
node.removeFromParent()
let transition = SKTransition.fade(withDuration: 1)
self.gameScene = SKScene(fileNamed: "GameOverScene")
self.gameScene.scaleMode = .aspectFit
self.view?.presentScene(self.gameScene, transition: transition)
}
}
}
我先调用此函数两次,先在override func didMove()
:
override func didMove(to view: SKView) {
createHUD()
createBall(forTrack: track)
}
在override func touchesBegan
中排名第二:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.previousLocation(in: self)
let node = self.nodes(at: location).first
if node?.name == "BALL" {
currentScore += ballValue
player?.removeFromParent()
createBall(forTrack: track)
}
else {
let transition = SKTransition.fade(withDuration: 1)
gameScene = SKScene(fileNamed: "GameOverScene")
gameScene.scaleMode = .aspectFit
self.view?.presentScene(gameScene, transition: transition)
}
}
}
更新
行self.enumerateChildNodes(withName: "BALL") { (node: SKNode, nil) in
有效,因此它不是子父关系问题。 if statement
无效。
答案 0 :(得分:2)
阅读你的代码我认为它不是一个解决方案,而是一个不同的方法。这些建议将使您的生活更轻松:
player = SKSpriteNode(imageNamed: "small")!
,因为如果初始化失败,您实际上想要崩溃,那么您可以摆脱所有?for touch in touches {
,因为它更易于管理let location = touch.previousLocation(in: self)
您的意思可能是let location = touch.location(in: self)
self.enumerateChildNodes(withName: "BALL") {
拨入更新通话,而不是每次触摸屏幕时如果这还不够,请随意发布最少量的代码来制作游乐场并让我为您测试:]