Search code examples
c++cocos2d-xbox2dcocos2d-x-3.0

Cocos2D/Box2d Setting velocity in only one axis


I'm trying to simulate some real jump physics with setVelocity using Box2d in Cocos2d x C++. My commands are like:

switch (keyCode){
case EventKeyboard::KeyCode::KEY_LEFT_ARROW:
    physicsBody->setVelocity(Vec2(75, 0));
    mySprite1->setPhysicsBody(physicsBody3);
break;
case EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
    physicsBody3->setVelocity(Vec2(-75,0));
    mySprite1->setPhysicsBody(physicsBody3);
break;
case EventKeyboard::KeyCode::KEY_UP_ARROW:
    physicsBody3->setVelocity(Vec2(0,200));
    mySprite1->setPhysicsBody(physicsBody3);
break;

}

However, as it is clear to me, whenever i change the velocity in one axis, the other axis gets one. The problem is: i'm unable to run and jump (the jump stops the running).

I need some way to change the velocity in only one axis at a time, so that my jump don't interfere with my run. That or another way to do tat exact same thing. I'm open to ideas regarding the physics since i'm a newbie in game programming.


Solution

  • You should use the ApplyLinearImpulse to get the effect that you are looking for.

    // Apply linear impulse only in x-direction
    physicsBody->ApplyLinearImpulse(b2Vec(75, 0),  physicsBody->GetPosition(), true);
    // Apply the jump impulse
    physicsBody->ApplyLinearImpulse(b2Vec(0, 200),  physicsBody->GetPosition(), true);
    

    The above code will apply impulse and add to the current velocity. Which means that when you jump you will keep moving in the x-direction. This is code from one of my projects so I can confirm that it works.