SpriteKit中的正弦波运动

kha*_*led 10 ios sprite-kit

我想从屏幕的第一个点到屏幕的最后一个点进行正弦波运动,与屏幕的大小无关.

这是我的代码,但它无法正常工作:

 SKSpriteNode* RedBird = (SKSpriteNode*)[self childNodeWithName:@"RedBird"];
CGPoint currentPoint=CGPointMake(-60,0);
double width=self.frame.size.width/4;
CGPoint cp1=CGPointMake(width, self.frame.size.height/2);
CGPoint cp2=CGPointMake((width*3), 0);
CGPoint e=CGPointMake(self.frame.size.width+200, 0);


CGMutablePathRef cgpath = CGPathCreateMutable();


CGPathMoveToPoint(cgpath,NULL, currentPoint.x, currentPoint.y);
CGPathAddCurveToPoint(cgpath, NULL, cp1.x, cp1.y, cp2.x, cp2.y, e.x, e.y);



[RedBird runAction:[SKAction group:@[[SKAction repeatActionForever:RedBirdAnimation],[SKAction followPath:cgpath asOffset:YES orientToPath:NO duration:12.0]]]];


CGPathRelease(cgpath);
Run Code Online (Sandbox Code Playgroud)

ABa*_*ith 13

我同意@Gord,因为我认为SKAction这是最好的方式.但是,当您可以使用该sin功能时,无需近似正弦曲线.

首先,你需要π,因为它对计算有用:

// Defined at global scope.
let ? = CGFloat(M_PI)
Run Code Online (Sandbox Code Playgroud)

其次,扩展SKAction(在Objective-C中这将通过类别完成)以轻松创建一个SKAction振荡有问题的节点:

extension SKAction {
    static func oscillation(amplitude a: CGFloat, timePeriod t: CGFloat, midPoint: CGPoint) -> SKAction {
        let action = SKAction.customActionWithDuration(Double(t)) { node, currentTime in
            let displacement = a * sin(2 * ? * currentTime / t)
            node.position.y = midPoint.y + displacement
        }

        return action
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中:amplitude是振荡的高度; timePeriod是一个完整周期的时间,midPoint是振荡发生的点.公式displacement来自简谐运动方程.

第三,将所有这些放在一起.您可以组合SKAction.oscillation动作SKAction.moveByX并使精灵沿曲线的路径移动.

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
        let node = SKSpriteNode(color: UIColor.greenColor(), size: CGSize(width: 50, height: 50))
        node.position = CGPoint(x: 25, y: size.height / 2)
        self.addChild(node)

        let oscillate = SKAction.oscillation(amplitude: 200, timePeriod: 1, midPoint: node.position)
        node.runAction(SKAction.repeatActionForever(oscillate))
        node.runAction(SKAction.moveByX(size.width, y: 0, duration: 5))
    }
}
Run Code Online (Sandbox Code Playgroud)


The*_*erg 0

我会创建一个基于更新所有游戏元素的游戏循环,而不是依赖 SKActions。SKActions 通常是一种执行动画的方法,用于游戏元素的连续移动,制作一个简单的引擎并让它更新红色小鸟的位置。