Cocos2d - 以正弦波运动将精灵从A点移动到B点

时间:2013-08-23 22:15:44

标签: ios cocos2d-iphone ccsprite ccaction

最好的方法是什么?我看到了CCEaseSineInOut操作,但它看起来不像是用来做这个。

我需要从屏幕的一侧移动到另一侧。精灵应该在屏幕上以正弦波模式移动。

1 个答案:

答案 0 :(得分:0)

我总是希望完全控制CCNode动作。我只使用CCAction来做非常基本的事情。虽然你的案例听起来很简单,可能与CCAction s有关,但我会告诉你如何随着时间的推移根据任何函数移动CCNode。您还可以使用相同的技术更改比例,颜色,不透明度,旋转甚至锚点。

@interface SomeLayer : CCLayer
{
    CCNode *nodeToMove;
    float t; // time elapsed
}
@end

@implementation SomeLayer

// Assumes nodeToMove has been created somewhere else
-(void)startAction
{
    t = 0;

    // updateNodeProperties: gets called at the framerate
    // The exact time between calls is passed to the selector
    [self schedule:@selector(updateNodeProperties:)];
}

-(void)updateNodeProperties:(ccTime)dt
{
    t += dt;

    // Option 1: Update properties "differentially"
    CGPoint velocity = ccp( Vx(t), Vy(t) ); // You have to provide Vx(t), and Vy(t)
    nodeToMove.position = ccpAdd(nodeToMove.position, ccpMult(velocity, dt));
    nodeToMove.rotation = ...
    nodeToMove.scale = ...
    ...

    // Option 2: Update properties non-differentially
    nodeToMove.position = ccp( x(t), y(t) ); // You have to provide x(t) and y(t)
    nodeToMove.rotation = ...
    nodeToMove.scale = ...
    ...

   // In either case, you may want to stop the action if some condition is met
   // i.e.)
   if(nodeToMove.position.x > [[CCDirector sharedDirector] winSize].width){
       [self unschedule:@selector(updateNodeProperties:)];
       // Perhaps you also want to call some other method now
       [self callToSomeMethod];
   }
}

@end

针对您的具体问题,您可以将选项2与x(t) = k * t + cy(t) = A * sin(w * t) + d一起使用。

数学笔记#1: x(t)y(t)称为位置参数化。 Vx(t)Vy(t)是速度参数化。

数学笔记#2:如果您已经学过微积分,很明显选项2可以防止位置误差累积(特别是对于低帧速率)。如果可能,请使用选项2.但是,如果不考虑精度或用户输入正在积极更改参数化,则通常更容易使用选项1.

使用CCAction有很多好处。他们会在特定时间为您处理其他功能。它们会被跟踪,以便您可以轻松地暂停它们并重新启动它们,或者对它们进行计数。

但是当你真的需要管理节点时,这就是这样做的方法。例如,对于位置的复杂或复杂公式,更改参数化比了解如何在CCAction中实现该参数化要容易得多。