Sine Wave Motion In SpriteKit

前端 未结 3 752
萌比男神i
萌比男神i 2021-01-02 07:25

I want to make sine wave motion from the first point in the screen to the last Point in the screen, independent on the size of the screen.

Here is my code, but it d

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-02 07:35

    This is an old post but I wanted to post an answer to make it google-able. I made this function in a subclass of SKSpriteNode that made the sprite go in an approximated sine wave from one side to the other.

    It's in swift, but could be easily done in objective C. Also, you'd want to be more intelligent and put the path building in a loop, but I just kept it unlooped to make the math easy to understand.

    (I don't disagree with the game loop answer but it kind of goes against the philosophy of Sprite Kit)

    func setSineAction()
    {
        let scene = self.parent as! SKScene
    
        let y42 = scene.size.height/2
        let x1 = scene.size.width
        let x2 = scene.size.width * 0.875
        let x3 = scene.size.width * 0.750
        let x4 = scene.size.width * 0.625
        let x5 = scene.size.width * 0.500
        let x6 = scene.size.width * 0.375
        let x7 = scene.size.width * 0.250
        let x8 = scene.size.width * 0.125
        let x9 = 0.0 as CGFloat
    
        let path = CGPathCreateMutable();
        CGPathMoveToPoint(path, nil, x1, y42)
        CGPathAddQuadCurveToPoint(path, nil, (x1/2)+(x2/2), scene.size.height*0.7, x2, y42)
        CGPathAddQuadCurveToPoint(path, nil, (x2/2)+(x3/2), scene.size.height*0.3, x3, y42)
        CGPathAddQuadCurveToPoint(path, nil, (x3/2)+(x4/2), scene.size.height*0.7, x4, y42)
        CGPathAddQuadCurveToPoint(path, nil, (x4/2)+(x5/2), scene.size.height*0.3, x5, y42)
        CGPathAddQuadCurveToPoint(path, nil, (x5/2)+(x6/2), scene.size.height*0.7, x6, y42)
        CGPathAddQuadCurveToPoint(path, nil, (x6/2)+(x7/2), scene.size.height*0.3, x7, y42)
        CGPathAddQuadCurveToPoint(path, nil, (x7/2)+(x8/2), scene.size.height*0.7, x8, y42)
        CGPathAddQuadCurveToPoint(path, nil, (x8/2)+(x9/2), scene.size.height*0.3, x9, y42)
    
        self.runAction(SKAction.followPath(path, asOffset: false, orientToPath: false, duration: 10))
    
    }
    

提交回复
热议问题