我正在尝试设置一个围绕固定点旋转的SKShapeNode
取决于用户的滑动手势。这样做我正在使用回答here.
当我将节点设置为矩形时 - 它工作正常,问题是当我尝试将节点设置为圆形时(因为我需要它)。我不知道为什么会发生这种情况,以及它与众不同之处。
这是有效的代码(SKShapeNode
为矩形):
override func didMove(to view: SKView) {
let ball = SKShapeNode(rect: CGRect(x: 100, y: 100, width: 100, height: 100))
ball.fillColor = SKColor.red
ball.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
ball.name = "BALL"
ball.physicsBody = SKPhysicsBody(circleOfRadius: 200)
ball.physicsBody?.angularDamping = 0.25
ball.physicsBody?.pinned = true
ball.physicsBody?.affectedByGravity = false
self.addChild(ball)
let om = 5.0
let er = 4.0
let omer = atan2(om, er)
print("om = \(om), er = \(er), atan2(omer) = \(omer)")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in:self)
let node = atPoint(location)
if node.name == "BALL" {
let dx = location.x - node.position.x
let dy = location.y - node.position.y
// Store angle and current time
startingAngle = atan2(dy, dx)
startingTime = touch.timestamp
node.physicsBody?.angularVelocity = 0
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
let location = touch.location(in:self)
let node = atPoint(location)
if node.name == "BALL" {
let dx = location.x - node.position.x
let dy = location.y - node.position.y
let angle = atan2(dy, dx)
// Calculate angular velocity; handle wrap at pi/-pi
var deltaAngle = angle - startingAngle!
if abs(deltaAngle) > CGFloat.pi {
if (deltaAngle > 0) {
deltaAngle = deltaAngle - CGFloat.pi * 2
}
else {
deltaAngle = deltaAngle + CGFloat.pi * 2
}
}
let dt = CGFloat(touch.timestamp - startingTime!)
let velocity = deltaAngle / dt
node.physicsBody?.angularVelocity = velocity
// Update angle and time
startingAngle = angle
startingTime = touch.timestamp
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
startingAngle = nil
startingTime = nil
}
但是当我将SKShapeNode
(我的didMove
函数内部)更改为圆圈时,这是不行的 - 这是更改的代码:
override func didMove(to view: SKView) {
let ball = SKShapeNode(circleOfRadius: 200)
ball.fillColor = SKColor.red
ball.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
ball.name = "BALL"
ball.physicsBody = SKPhysicsBody(circleOfRadius: 200)
ball.physicsBody?.angularDamping = 0.25
ball.physicsBody?.pinned = true
ball.physicsBody?.affectedByGravity = false
self.addChild(ball)
}
有没有人看到/知道我的错误是什么?
答案 0 :(得分:1)
你怎么能看到形状在转动?你在shapenode里面有什么东西,你可以看到旋转的纹理吗?
旋转圆形的shapenode看起来与静态的相同。在场景的更新循环中抓住球并打印其zRotation以查看它是否实际转动。
override func update(_ currentTime: TimeInterval) {
var ball: SKShapeNode = childNodeWithName("BALL") as SKShapeNode
print(ball.zRotation)
}
(这段代码是在没有访问Swift的情况下编写的,因此您可能需要稍微修改一下语法)
请记住,zRotation是以弧度为单位,所以它可能看起来不怎么样,但它正在改变,然后SKShapeNode实际上正在旋转,你只是看不到它。 你必须添加一个可见的子节点。