[英]How do you add multiple nodes to scene and move all of them at once. swift. sprite kit
I am new to swift and spriteKit. 我是Swift和SpriteKit的新手。 I am creating a side scrolling game.
我正在创建一个侧滚动游戏。 I want it to add multiple nodes(called Impenitrible) from the right side of the screen at any height and move left.
我希望它从屏幕的右侧以任意高度添加多个节点(称为Impenitrible),然后向左移动。 My function for creating the "Impenitrible" node is :
我创建“不可侵犯”节点的功能是:
func spawnImpenitrible(){
Impenitrible.physicsBody = SKPhysicsBody(rectangleOfSize: Impenitrible.size)
let actionDone = SKAction.removeFromParent()
var MinValue = sand.size.height
var MaxValue = self.size.height - Impenitrible.size.height / 2
var spawnPoint = UInt32(MaxValue - MinValue)
Impenitrible.position = CGPoint(x: self.size.width - 60 , y: CGFloat(arc4random_uniform(spawnPoint)))
Impenitrible.physicsBody?.categoryBitMask = physicsCategory.impenitrible
Impenitrible.physicsBody?.contactTestBitMask = physicsCategory.sub
Impenitrible.physicsBody?.affectedByGravity = false
Impenitrible.physicsBody?.dynamic = true
self.addChild(Impenitrible)
}
I call this function with: 我称这个功能为:
var impenitribleTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: Selector("spawnImpenitrible"), userInfo: nil, repeats: true)
I move it by subtracting a number from the x position in the "Update" function. 我通过从“更新”功能的x位置减去一个数字来移动它。
It works fine adding Impenitrible once. 一次添加Impenitrible效果很好。 but once it calls the function again the app crashes with error of :
但一旦再次调用该函数,该应用就会崩溃,并显示错误消息:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attemped to add a SKNode which already has a parent where did i go wrong? 由于未捕获的异常“ NSInvalidArgumentException”而终止应用程序,原因:“试图添加已经具有父级的SKNode,我在哪里出错了? Any help would be great!
任何帮助将是巨大的! Thank you.
谢谢。
First, I want to point out that your line of code: let actionDone = SKAction.removeFromParent()
is effectively useless because you never call runAction
to use it. 首先,我想指出您的代码行:
let actionDone = SKAction.removeFromParent()
实际上是无用的,因为您永远不会调用runAction
来使用它。
The error message sums it up quite nicely. 该错误消息总结得很好。 "Attempted to add a SKNode which already has a parent".
“尝试添加已经具有父级的SKNode”。 You never actually call
removeFromParent()
. 您实际上从未调用过
removeFromParent()
。
Adding Impenitrible
once works fine as you found out, because at the start, Impenitrible
has no parent. 如发现的那样,添加
Impenitrible
可以正常工作,因为一开始, Impenitrible
没有父级。 Subsequent calls will have a conflict because Impenitrible
already has the parent that was added via the first call. 后续调用会有冲突,因为
Impenitrible
已经拥有通过第一个调用添加的父级。
A quick and dirty fix is to do a runAction(SKAction.removeFromParent())
before the next call of spawnImpenitrible
, somewhere, referencing Imprenitrible
. 一个快速而肮脏的解决方法是在下一次调用
spawnImpenitrible
之前的某个地方执行runAction(SKAction.removeFromParent())
,并引用Imprenitrible
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.