SpriteKit 中的正弦波运动

2023-11-20

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

这是我的代码,但它不能正常工作:

 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);

我同意@Gord,我认为SKAction这是最好的方法。但是,当您可以使用以下函数时,无需近似正弦曲线:sin功能。

首先,您需要 π,因为它对于计算很有用:

// Defined at global scope.
let π = CGFloat(M_PI)

其次,延长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
    }
}

在上面的代码中: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))
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpriteKit 中的正弦波运动 的相关文章

随机推荐