使用全局函数永远重复一个动作
Repeating an action forever with a global function
我有一个需要不断向上移动的矩形,但它也是全局声明的,这样我就可以在多个地方调用它:
var obstacle = SKNode!
override func didMoveToView {
obstacle = rectangle()
}
func rectangle() -> SKNode {
let rect = SKSpriteNode(imageNamed: "Rectangle@x2")
rect.size = CGSizeMake(30, 30)
rect.position = CGPointMake(210, -250)
rect.physicsBody?.categoryBitMask = PhysicsCatagory.littleRect
rect.physicsBody?.contactTestBitMask = PhysicsCatagory.bigRect
rect.physicsBody?.collisionBitMask = 0
rect.physicsBody = SKPhysicsBody(rectangleOfSize: rect.size)
rect.physicsBody?.dynamic = true
rect.physicsBody?.affectedByGravity = false
rect.runAction(
SKAction.moveByX(0, y: 1200,
duration: NSTimeInterval(6.5)))
addChild(rect)
return rect
}
When I attempt to run it as an action repeating forever like so, i get the error "cannot convert value of type SKNode to argument runBlock" :
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock(rectangle),
SKAction.waitForDuration(4.0)])))
那么有没有办法为这样设置的函数声明这种动作?先感谢您。
首先,这个var obstacle = SKNode!
会产生一个错误。你应该像这样声明一个隐式解包的可选:
var obstacle:SKNode!
关于主要问题(没有分析代码实际执行的逻辑,)...您正在将 SKNode
class 的实例传递给 +runBlock: 方法(它接受闭包),因此错误。要解决此问题,您必须传递一个闭包,如下所示:
override func didMoveToView(view: SKView) {
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock({[unowned self] in self.rectangle()}),
SKAction.waitForDuration(4.0)])))
}
我有一个需要不断向上移动的矩形,但它也是全局声明的,这样我就可以在多个地方调用它:
var obstacle = SKNode!
override func didMoveToView {
obstacle = rectangle()
}
func rectangle() -> SKNode {
let rect = SKSpriteNode(imageNamed: "Rectangle@x2")
rect.size = CGSizeMake(30, 30)
rect.position = CGPointMake(210, -250)
rect.physicsBody?.categoryBitMask = PhysicsCatagory.littleRect
rect.physicsBody?.contactTestBitMask = PhysicsCatagory.bigRect
rect.physicsBody?.collisionBitMask = 0
rect.physicsBody = SKPhysicsBody(rectangleOfSize: rect.size)
rect.physicsBody?.dynamic = true
rect.physicsBody?.affectedByGravity = false
rect.runAction(
SKAction.moveByX(0, y: 1200,
duration: NSTimeInterval(6.5)))
addChild(rect)
return rect
}
When I attempt to run it as an action repeating forever like so, i get the error "cannot convert value of type SKNode to argument runBlock" :
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock(rectangle),
SKAction.waitForDuration(4.0)])))
那么有没有办法为这样设置的函数声明这种动作?先感谢您。
首先,这个var obstacle = SKNode!
会产生一个错误。你应该像这样声明一个隐式解包的可选:
var obstacle:SKNode!
关于主要问题(没有分析代码实际执行的逻辑,)...您正在将 SKNode
class 的实例传递给 +runBlock: 方法(它接受闭包),因此错误。要解决此问题,您必须传递一个闭包,如下所示:
override func didMoveToView(view: SKView) {
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock({[unowned self] in self.rectangle()}),
SKAction.waitForDuration(4.0)])))
}