I didn't bother with coding it too properly because it was a quick test, but it should be clear enough to learn how to use Box2D with Irrlicht.
Also WORLD_PHYS_SCALE is defined as 30.0f because Box2D measures the world in meters and in order to keep things on a smaller scale and consistent with Irrlicht's world coordinates I have to divide and multiply coordinates by WORLD_PHYS_SCALE where appropriate.
I hope this helps somebody.
Code: Select all
/* Header */
#ifndef _INCLUDE_TESTNODE_H_
#define _INCLUDE_TESTNODE_H_
#include "maze.h"
class World;
class TestNode
{
private:
IMeshSceneNode* _Node;
b2Body* _Body;
World* _World;
public:
TestNode(World* world);
~TestNode(void);
void think(void);
};
#endif
/* Code file */
#include "maze.h"
#include "testnode.h"
#include "world.h"
TestNode::TestNode(World* world)
{
ICameraSceneNode* cam = g_pIrrDevice->getSceneManager()->getActiveCamera();
_Node = g_pIrrDevice->getSceneManager()->addSphereSceneNode(5.0f);
g_pIrrDevice->getSceneManager()->addLightSceneNode(_Node);
_Node->setPosition(
vector3df( cam->getPosition().X, (WORLD_CELL_SIZE/2.0f), cam->getPosition().Z )
);
b2BodyDef bDef;
bDef.type = b2_dynamicBody;
bDef.allowSleep = true;
bDef.position = b2Vec2( cam->getPosition().X / WORLD_PHYS_SCALE, cam->getPosition().Z / WORLD_PHYS_SCALE );
b2CircleShape shape;
shape.m_radius = 5.0f / WORLD_PHYS_SCALE;
b2FixtureDef fxDef;
fxDef.shape = &shape;
fxDef.density = 1;
fxDef.restitution = 0.75f;
fxDef.friction = 0.5f;
fxDef.userData = (void*)this;
_Body = world->getPhysicalWorld()->CreateBody(&bDef);
_Body->CreateFixture(&fxDef);
vector3df vecDir;
vecDir.X = cam->getTarget().X - cam->getPosition().X;
vecDir.Y = cam->getTarget().Y - cam->getPosition().Y;
vecDir.Z = cam->getTarget().Z - cam->getPosition().Z;
vecDir.normalize();
_Body->ApplyLinearImpulse(
b2Vec2(vecDir.X, vecDir.Z),
_Body->GetPosition()
);
}
void TestNode::think(void)
{
b2Vec2 physPos = _Body->GetPosition();
vector3df irrPos = _Node->getPosition();
irrPos.X = physPos.x * WORLD_PHYS_SCALE;
irrPos.Z = physPos.y * WORLD_PHYS_SCALE;
_Node->setPosition(irrPos);
}

