如何用触摸旋转SpriteNode?

时间:2017-03-31 17:43:20

标签: swift xcode sprite-kit skspritenode swift-playground

如何通过触摸在固定点上旋转SpriteKit节点。所以它随着用户拖动他的手指而转动。我也希望能够获得转速。 (之前曾问过这个问题,但我想知道如何使用SpriteKit) Swift 3游乐场

到目前为止我已经得到了这个有效但有时我得到var deltaAngle = angle的错误 - startingAngle!错误 - "在打开可选值&#34时出乎意料地发现nil;

class GameScene: SKScene {
var startingAngle:CGFloat?
var startingTime:TimeInterval?


override func didMove(to view: SKView) {
    let wheel = SKSpriteNode(imageNamed: "IMG_6797.PNG" )

    wheel.position = CGPoint(x: 200, y: 200)

    wheel.name = "wheel"
    wheel.setScale(0.5)
    wheel.physicsBody = SKPhysicsBody(circleOfRadius: wheel.size.width/2)
    // Change this property as needed (increase it to slow faster)
    wheel.physicsBody!.angularDamping = 4
    wheel.physicsBody?.pinned = true
    wheel.physicsBody?.affectedByGravity = false
    addChild(wheel)
}

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 == "wheel" {
            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 == "wheel" {
            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

            startingAngle = angle
            startingTime = touch.timestamp
        }
    }
}



override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    startingAngle = nil
    startingTime = nil
}

}

1 个答案:

答案 0 :(得分:0)

该错误意味着它所说的内容。最有可能的是,“wheel”没有被touchesBegan触及,而是在touchesMoved中注册,导致startingAngle没有被设置为任何东西而且没有。

如果用户没有开始接触方向盘,你可能不希望你的车轮旋转,我会在touchMoved中添加一个后卫

...
let angle = atan2(dy, dx)

guard startingAngle != nil else {return} //Exit the function if starting angle was never set

var deltaAngle = angle - startingAngle!
...