Game Development Reference
In-Depth Information
Once you start using this particular code, you'll notice that, depending on the distance
myNode has to move, its speed will be different. This very common problem has a
simple solution: calculate the distance from the current position to the target position
and then divide it by the speed you want the node to move. The result is the correct
duration to have the node move to the target position at the same speed, regardless of
where the node and target positions are.
// have myNode move at a fixed speed to any position
CGPoint targetPos = CGPointMake(100, 200);
float speed = 10; // in pixels per second
float duration = ccpDistance(myNode.position, targetPos) / speed;
CCMoveTo* move = [CCMoveTo actionWithDuration:duration position:targetPos];
[myNode runAction:move];
By the way, you don't have to remove an action. Once an action has completed its task,
it removes itself from the node automatically and releases the memory it uses. That,
unfortunately, is also actions' greatest weakness: you can't re-use them. If you need the
same action or action sequence later on, you have to create new instances of the action
Caution A tip found in the official cocos2d documentation recommends
simply “re-initializing” an action by sending it the appropriate initWith. .
. message again. But this is dangerous and can lead to memory leaks and pos-
sibly crashes because not every action class can be safely re-initialized. And for
some actions, it simply doesn't have the desired effect.
If you keep a reference to an action, maybe in an attempt to re-use it later, and then use
it in multiple messages to runAction , you'll notice that either the action has no ef-
fect or the node behaves unexpectedly. The simplest way to provoke this issue is to try
to use the same action on two different nodes, like so:
CCMoveTo* move = [CCMoveTo actionWithDuration:duration position:targetPos];
[myNode runAction:move]; // this node will stay put
[otherNode runAction:move]; // this node will move
Search Nedrilad ::

Custom Search