How to reverse the direction of path followed by sprite in an SKAction midway?

走远了吗. 提交于 2019-12-06 05:44:32
Max Kortge

I'm assuming your trying to get it to go in the opposite direction on when the player touches the screen. Try creating a function for both of the directions, one for clockwise and anti-clockwise in these functions add your method of making the path. I would use this code to complete this task as I don't find any errors:

 func moveClockWise() {

    let dx = Person.position.x - self.frame.width / 2
    let dy = Person.position.y - self.frame.height / 2

    let rad = atan2(dy, dx)

    let Path = UIBezierPath(arcCenter: CGPoint(x: self.frame.width / 2, y: self.frame.height / 2), radius: 120, startAngle: rad, endAngle: rad + CGFloat(M_PI * 4), clockwise: true)
    let follow = SKAction.followPath(Path.CGPath, asOffset: false, orientToPath: true, speed: 200)
    Person.runAction(SKAction.repeatActionForever(follow).reversedAction())

}

This is just my preferred way, and for anti-clockwise, just create another function just reversing the code.

Now above the didMoveToView add these variables:

var Person = SKSpriteNode()

var Path = UIBezierPath()

var gameStarted = Bool()

var movingClockwise = Bool()

These basically define your Person as a SKSpriteNode() your Path as a UIBezierPath() etc. Of course you would have your Person.position = position and Person = SKSpriteNode(imageNamed: "name") under your didMoveToView to create the sprite.

After this, under the override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {, you want to use the gameStarted bool variable to detect wether it is running, if it is set the bool to true and change it's direction.

if gameStarted == false {

        moveClockWise()
        movingClockwise = true
        gameStarted = true

    }
    else if gameStarted == true {

        if movingClockwise == true {

            moveCounterClockWise()
            movingClockwise = false

        }
        else if movingClockwise == false {

            moveClockWise()
            movingClockwise = true

        }
    }

Basically the first line of code checks whether the bool is false (which it is because nothing has happened to it and it has just loaded), and runs the moveClockwise function and sets the moveClockwise bool to true and the gameStarted bool to true as well. Everything else is pretty self explanatory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!