SKAction.rotate 不工作?

SKAction.rotate not working?

我正在尝试创建一个节点并使用一个动作为其 zRotation 属性 设置动画,但是,当尝试 运行 该动作时,我节点的 zRotation 属性 是没有改变。我不确定为什么这不起作用。

import UIKit
import SpriteKit

let aim = SKSpriteNode()

print(aim.zRotation)
aim.zRotation = CGFloat(Double.pi/2)
print(aim.zRotation)

let myAction = SKAction.rotate(toAngle: CGFloat(3.14), duration: 0)
aim.run(myAction)
print(aim.zRotation)

带有输出的代码图像

仅当您的节点位于视图中依次显示的场景中时,才会评估 SKAction:

An SKAction object is an action that is executed by a node in the scene (SKScene). ... When the scene processes its nodes, actions associated with those nodes are evaluated.

(来自 Apple's SKAction documentation

目前你没有这些东西,所以行动仍然处于休眠状态。有关向场景添加节点并在 playground 中显示该场景的示例,请参阅 this from Swift Studies

我猜你想实现这样的目标

问题

您的代码中存在一些错误:

  1. 持续时间为 0 的动作将立即应用更改,最好设置一个更大的值。
  2. 您没有在 Playground 中展示 SKView
  3. 你的SKSpriteNode没有镜像

解决方案

在 Playground select View > Assistant > Show Assistant Editor 以在右侧打开一个面板,我们将在其中添加 SKView。

现在添加此代码并等待红色方块出现在助理编辑器中。

import PlaygroundSupport
import SpriteKit

let sceneView = SKView(frame: CGRect(x:0 , y:0, width: 500, height: 500))

let scene = SKScene(size: CGSize(width: 500, height: 500))
scene.anchorPoint.x = 0.5
scene.anchorPoint.y = 0.5
sceneView.showsFPS = true
sceneView.presentScene(scene)
PlaygroundPage.current.liveView = sceneView

let square = SKShapeNode(rect: CGRect(x: 0, y: 0, width: 100, height: 100))
square.fillColor = .red
scene.addChild(square)
square.run(.rotate(toAngle: 3.14, duration: 20))