我总是喜欢完全控制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 中弄清楚如何实现该参数化要容易得多。