Xcode SpriteKit SKAction 不改变 SKSpriteNode 的属性?

Xcode SpriteKit SKAction not changing properties of an SKSpriteNode?

如果我在节点上创建一个 SKSpriteNode 和 运行 一个 SKAction,则模拟器上的操作 运行s,但是节点的属性有没有改变。 例如。在以下示例中,在模拟器中,节点从 (50,50) 开始并在 1 秒内移动到 (0,0)。但是,末尾的打印语句打印 (50,50) 而不是新位置 (0,0)

let test = SKSpriteNode()

test.position = CGPoint(x: 50.0, y: 50.0)
test.size = CGSize(width: 20.0, height: 20.0)
test.color = UIColor.black
addChild(test)

test.run(SKAction.move(to: CGPoint(x: 0, y: 0), duration: 1.0))
print("(\(test.position.x), \(test.position.y))")

我能想到的唯一原因是打印语句在SKAction执行之前执行。如果是这种情况,那么稍后如何执行依赖于获取 SKSpriteNode?

的位置值的代码

节点的初始位置在移动到所需位置之前已打印出来,您需要做的是在节点到达所需位置时打印节点的位置。

您可以使用如下顺序修复它:

let test = SKSpriteNode()
test.position = CGPoint(x: 50.0, y: 50.0)
test.size = CGSize(width: 20.0, height: 20.0)
test.color = UIColor.red
addChild(test)

let moveAction = SKAction.move(to: CGPoint(x: 0, y: 0), duration: 1.0)
let printAction = SKAction.run {
  print("(\(test.position.x), \(test.position.y))")
}
let sequence = SKAction.sequence([moveAction, printAction])

test.run(sequence)

已经测试过了,希望对你有帮助

祝你好运!! :]

The only reason I can think of is that the print statement executes before the SKAction is executed.

你完全正确!

then how do I execute code later on that relies on getting the position values of the SKSpriteNode?

通过组合 SKAction.sequenceSKAction.run 方法调用。

sequence 方法 returns 由一系列 运行 一个接一个的动作组成的动作。

run 方法 returns 当 运行 执行您作为参数传入的代码块的操作。

您想在 "move" 完成后打印位置,因此创建一个这样的操作:

let runCodeAction = SKAction.run { 
    print("(\(test.position.x), \(test.position.y))") 
}

然后,使用 sequence 创建一系列操作:

let sequence = SKAction.sequence(
    [SKAction.move(to: CGPoint(x: 0, y: 0), duration: 1.0), runCodeAction])

现在运行这个序列:

test.run(sequence)

在 SpriteKit 中,SKAction class 有很多实例方法,但是 你不需要像 SKAction.sequence 添加更多的代码和另一个 SKAction 打印你的位置。

事实上你有 run(_:completion) ,你可以找到

的官方文档 here

have a completion block called when the action completes

所以你的代码是按原样完成的,只需像这个例子一样添加完成语法:

test.run(SKAction.move(to: CGPoint(x: 0, y: 0), duration: 1.0), completion:{ 
   print("(\(test.position.x), \(test.position.y))")
})