How to apply a force to a physics body 3.17?

How to apply a force to a physics body 3.17?


I was reading the documentation about the physics engine, it seems like there are a lot of wrappers around box2d so no need to include it and instead work with the classes provided by cocos, so that’s what i did:

bool HelloWorld::init()
if( !Scene::initWithPhysics() )
    return false;

auto listener = EventListenerKeyboard::create();

listener->onKeyPressed = CC_CALLBACK_2(HelloWorld::onKeyPressed, this);
listener->onKeyReleased = CC_CALLBACK_2(HelloWorld::onKeyReleased, this);

_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
auto physicsBody = PhysicsBody::createBox(Size(37.0f, 32.0f), PhysicsMaterial(0.1f, 
1.0f, 0.0f));


this->sprite = Sprite::create();

return true;

void HelloWorld::onKeyPressed(EventKeyboard::KeyCode keyCode, Event * event)
case EventKeyboard::KeyCode::KEY_D:
	this->sprite->getPhysicsBody()->applyForce(Vec2(200.0f, 200.0f));

I applied a force to the sprite but when i pressed D it didn’t apply it, any tips?


Have you put a log statement in your case to make sure the key press is indeed working?

Also, our internal physics engine is based upon Chipmunk but yes chipmunk and box2d are similar enough.

Did you look at the example in cpp-tests? We should probably add more to the docs about this since we have working examples in cpp-tests.


@slackmoehrle Yes i did, the listener is working, i tried with this->sprite->getPhysicsBody()->applyImpulse(Vec2(0.0f, 80000.0f)); also and it worked just perfect, not sure why applyForce() is not working though.