Hi guys,
I've surveyed component-based game object system for a long time and created one for my current project.
I know its idea is dividing functionalities of game objects to several components to prevent deep class hierarchy. However, I still cannot figure out how to build my game upon component-based system.
For example, a character (controlled by player) fires a RPG. Then rocket flies over the sky, hits the building and then explodes. How do I code these events and logics into components?
Assume that the character, RPG, and rocket are game objects. Following is my approach
GameObject* character = scene->createGameObject("player", "character.xml");
character->getComponent<CharacterLogic>()->fireWeapon("RPG");
and somewhere inside CharacterLogic::fireWeapon(), there is a piece of code like this
GameObject* rpg = _scene->getGameObject("rocket");
rpg->getComponent<RpgLogic>()->fire();
Inside RpgLogic::fire()
GameObject* rocket = _scene->createGameObject(some_obj_name, "bullet_rocket.xml");
rocket->setPosition( this->getObject()->getPosition() + _offset );
rocket->getComponent<RigidPhysics>()->setVelocity( this->getObject()->getOrientation()*Vector3::AxisX()*_rocketSpeed );
There is a component RocketLogic inside the rocket. When RigidPhysics component of the rocket detects collision between the rocket and some other objects, it will send a message and notify RocketLogic component. So RocketLogic calls its member function RocketLogic::onContact() to trigger explosion effect.
//inside RocketLogic::onContact()
GameObject* explosionEffect = _scene->createGameObject( some_obj_name, "explosion.xml" );
explosionEffect->getComponent<ParticleEffect>()->run();
//I don't known whether it is appropriate to implement the explosion effect as a game object
I've noticed that my design has many drawbacks.
Every time you need to do some operation, you have to call getComponent with a specific component type as template arguments. So it takes some time for game object to find the component. (look up hash_map )
And if the specified component ( by getComponent ) doesn't exists in the game object, we need to do some error handling, and thus causing a lot of error handling code in my program.
Could anyone give me some suggestion?