SpriteKit中的正弦波运动 [英] Sine Wave Motion In SpriteKit
问题描述
我想使正弦波从屏幕的第一个点移动到屏幕的最后一个点,而与屏幕的大小无关.
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 doesn't work correctly:
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
函数时,无需近似正弦曲线.
I agree with @Gord, in that I think SKAction
s are the best way to go. However, there is no need to approximate the sine curve when you can use the sin
function.
首先,您需要π,因为它将对计算有用:
Firstly, you need π as it's going to be useful for the calculations:
// Defined at global scope.
let π = CGFloat(M_PI)
其次,扩展SKAction
(在Objective-C中,这将通过类别完成)以轻松创建SKAction
,使该节点振荡:
Secondly, extend SKAction
(in Objective-C this would be done with categories) to easily create an SKAction
that oscillates the node in question:
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
的公式来自简单谐波运动的方程.
In the code above: amplitude
is the height of the oscillation; timePeriod
is the time for one complete cycle and the midPoint
is the point around which the oscillation occurs. The formula for displacement
comes from the equations for Simple Harmonic Motion.
第三,将所有内容放在一起.您可以结合使用SKAction.oscillation
动作和SKAction.moveByX
来使精灵沿曲线的路径移动.
Thirdly, putting that all together. You can combine the SKAction.oscillation
action and SKAction.moveByX
to make the sprite move along the path of the curve.
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))
}
}
这篇关于SpriteKit中的正弦波运动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!