Follow the way back

I am creating a sprite for the orbit of a point, and for that I made a path followed by this sprite:

    let dx1 = base1!.position.x - self.frame.width/2
    let dy1 = base1!.position.y - self.frame.height/2

    let rad1 = atan2(dy1, dx1)

    path1 = UIBezierPath(arcCenter: circle!.position, radius: (circle?.position.y)! - 191.39840698242188, startAngle: rad1, endAngle: rad1 + CGFloat(M_PI * 4), clockwise: true)
    let follow1 = SKAction.followPath(path1.CGPath, asOffset: false, orientToPath: true, speed: 200)
    base1?.runAction(SKAction.repeatActionForever(follow1))

      

This works and the sprite starts to rotate around this point. The thing is, when the user touches the screen, I want the sprite to start rotating counterclockwise. To do this, I write the same code for clockwise rotation, but editing the last line:

base1?.runAction(SKAction.repeatActionForever(follow1).reversedAction())

      

But the problem is that even though it rotates counterclockwise, the sprite image is flipped horizontally. What can I do to avoid this? Or is there any other way to orbit the sprite through a point?

+1


source to share


1 answer


The direct way to rotate a sprite around a point (i.e., an orbit) is to create a container node, add the sprite at the node with an offset (relative to the center of the container), and rotate the container node. Here's an example of how to do it:



class GameScene: SKScene {
    let sprite = SKSpriteNode(imageNamed:"Spaceship")
    let node = SKNode()

    override func didMove(to view: SKView) {
        sprite.xScale = 0.125
        sprite.yScale = 0.125
        sprite.position = CGPoint (x:100, y:0)

        node.addChild(sprite)
        addChild(node)

        let action = SKAction.rotate(byAngle:CGFloat.pi, duration:5)

        node.run(SKAction.repeatForever(action), withKey:"orbit")
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let action = node.action(forKey: "orbit") {
            // Reverse the rotation direction
            node.removeAction(forKey:"orbit")
            node.run(SKAction.repeatForever(action.reversed()),withKey:"orbit")
            // Flip the sprite vertically
            sprite.yScale = -sprite.yScale
        }
    }
}

      

+1


source







All Articles