【问题标题】:Cocos2d - move a sprite from point A to point B in a sine wave motionCocos2d - 以正弦波运动将精灵从 A 点移动到 B 点
【发布时间】:2013-08-27 02:06:59
【问题描述】:

最好的方法是什么?我看到了 CCEaseSineInOut 操作,但它看起来不能用于执行此操作。

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

【问题讨论】:

  • 您可以使用贝塞尔曲线 - 请参阅 stackoverflow.com/questions/14589474/…
  • 如果你想实现正弦波模式,那么你必须使用 cceasesineinout 进行一些手动操作。对于一个正弦波周期,您必须使用 cceasesineinout 3 次。

标签: ios cocos2d-iphone ccsprite ccaction


【解决方案1】:

我总是喜欢完全控制CCNode 的动作。我只使用CCActions 做非常基本的事情。虽然您的情况听起来很简单,可以使用CCActions,但我将向您展示如何随着时间的推移根据任何函数移动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 + c 和 y(t) = A * sin(w * t) + d 一起使用。

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

数学笔记#2:如果您研究过微积分,很明显选项 2 可以防止位置误差随着时间的推移而累积(尤其是对于低帧速率)。如果可能,请使用选项 2。但是,当不关心准确性或用户输入正在积极更改参数化时,使用选项 1 通常更容易。

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

但是当你确实需要对节点进行一般管理时,这就是这样做的方式。例如,对于复杂或复杂的位置公式,更改参数化比在CCActions 中弄清楚如何实现该参数化要容易得多。

【讨论】:

  • 如何在 SpriteKit 中制作正弦波运动?
  • 什么是“k”、“t”、“c”、“w”和“d”?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多