Search code examples
cocos2d-iphone

Cocos2D: CCPhysicsNode and child sprite move with different speed


I'm following the tutorial here to mimic Flappy Bird. At the part to scroll the game scene:

- (void)update:(CCTime)delta {
    _hero.position = ccp(_hero.position.x + delta * scrollSpeed, _hero.position.y);
    _physicsNode.position = ccp(_physicsNode.position.x - (scrollSpeed *delta), _physicsNode.position.y);
    ...
}

Ideally the whole world will scroll left, and _hero (which is a child node of _physicsNode) move right with the same speed it would stay still on the screen. But when I run the code on simulator the _hero sprite just blast off to the right at the speed of light (about 10~20 times faster than the scrolling speed of _physicsNode). The _physicsNode and every other things inside it is scrolling left at normal speed as intended.

If I don't give _hero any movement it would scroll along with _physicsNode normally.

I have tried other method like using CCAction at game start:

CCAction *moveAction = [CCActionMoveBy actionWithDuration:1 position:ccp(-scrollSpeed,0)];
CCActionRepeatForever *repeatAction = [CCActionRepeatForever actionWithAction:(CCActionInterval *)moveAction];
[_physicsNode runAction:repeatAction];

And still get the same result. The speed value that _hero receive is always different from the speed that _physicsNode receive.

Could anyone explain to me why this is happening and how to fix it? I'm using cocos2d 3.3 if it helps.


Solution

  • I finally figured it out.

    The _hero node had its positionType set to CCPositionTypeNormalized (because I was trying to center him on the screen) while the _physicNode has its positionType as CCPositionTypePoints. Any change to the node's position (including movement actions) are based on the node's positionType. The result is that when I move the _hero node by 2, it doesn't move 2 points but 2% of the parent node's width instead.

    I fixed it by aligning the _hero on SpriteKit using CCPositionTypeNormalized, then switching it to CCPositionTypePoints at game start.