• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
  • entries
    11
  • comments
    15
  • views
    49772

My Component Base Entity System, Part 3

Sign in to follow this  
Followers 0
BeerNutts

1636 views

You probably notice I'm flying through these articles. Mainly, it's because I want to get these Component articles out of the way and get to writing a new game.

So, this time I'm going to go over some of the SmashPC specific Components. You can get the full Source code here:
SmashPcComp-12-23-11


So, here's a list of the components I have for the game, and what they do:
Camera - This component signifies where the center of the camera should be drawn within the game world. CUrrently, it's always on the Player, but, you could do cool things with it, like moving it to a remote-controlled entity for a short time.
Enemy - This component handles the logic for the enemy. It has 2 timers, one to control how often he turns towards the player, and one to control how often he fires his weapon.
EnemySpawn - This handles the releasing of the enemies into the world. When it's timer expires, it creates an ADD_ENTITY_EVENT for the Enemy.
GraphicsObject - Handles drawing it's entity if it's a sprite. It gets it's entity's physical component and finds the current camera location so it knows where to draw itself.
GraphicsShape - Same as GraphicsObject, except it deal with entities that are shapes, not sprites.
Input - Handles sending Input event to it's owner entity. Currently, only player is controlled, but, as with camera, could be moved around to other entities to do fun stuff.
PhysicalObject - Handles representing an entity in the physical world. It contains the location and the shape of the object. This object is given force, angle, and location. It is this object that all collisions originate via a callback from the physics library. The SetCollision() is used to detail what other type of entities it should get notified of collisions.
Player - Handles all the logic for controlling the player. It get input events and tells others where the player is (like the enemy).
Sound - Handles playing sounds on certain events. This component is controversial. I'm really not sure what it adds, since I typically can just play a sound whenever the event happens. But, I added it, and I'm using it, via the SetSound(), which plays a sound on a specific event.
Weaponry - Handles firing bullets, and, for a player, handles acquiring new weapons. Has a refire timer that, when expires, allows a new bullet to be fired.

Well take a look at the Input and Player Components here to get a better understanding of how it would work.

First, Input:


class TInput : public TComponent
{
public:

struct TInputData
{
uint32_t KeyMask;
uint32_t MouseX;
uint32_t MouseY;
};

TInput();
~TInput();

/******************************************************************
*
* OnFrameTick - Callback for a frame tick
*
*******************************************************************/
static void OnFrameTick(TEvent &Event, void *pThis);

/******************************************************************
*
* OnFrameTick - Callback for a frame tick
*
*******************************************************************/
void FrameTick(TEvent &Event);

protected:
virtual void Cleanup();
virtual void Initialize();

private:
sf::RenderWindow *mpApp;
bool mbWasKeyPressed;
uint32_t mMouseX, mMouseY;

};


The header is pretty simple. We create the TInputData struct to send during events. Otherwise, it gets notified every frame tick, and keeps the current mouse location and the main SFML Window.

Here's the source code.


/******************************************************************
*
* TInput - Constructor, simple
*
*******************************************************************/
TInput::TInput() :
TComponent(INPUT_COMPONENT)
{


mMouseX = 0;
mMouseY = 0;

mbWasKeyPressed = false;
}

/******************************************************************
*
* ~TInput - DeConstructor
*
*******************************************************************/
TInput::~TInput()
{

}


/******************************************************************
*
* OnFrameTick - Callback for a frame tick
*
*******************************************************************/
void TInput::OnFrameTick(TEvent &Event, void *pThis)
{
TInput *pInput =
reinterpret_cast(pThis);

pInput->FrameTick(Event);
}

/******************************************************************
*
* OnFrameTick - Callback for a frame tick
*
*******************************************************************/
void TInput::FrameTick(TEvent &Event)
{
const sf::Input& Input = mpApp->GetInput();
uint32_t Key;
TInputData InputData;
InputData.KeyMask = 0;
bool bMouse = false;

// Loop through the possible keys, and check what's
// being pushed
for (Key = (uint32_t)GAME_KEY_FIRST; Key < (uint32_t)GAME_KEY_MAX; Key++) {
if (Utilities::KeyIsDown(Input, (etGameKeys)Key)) {
InputData.KeyMask |= (1 << Key);
mbWasKeyPressed = true;
}
}

// Check for mouse movement
InputData.MouseX = Input.GetMouseX();
InputData.MouseY = Input.GetMouseY();

if (mMouseX != InputData.MouseX || mMouseY != InputData.MouseY) {
mMouseX =InputData.MouseX;
mMouseY = InputData.MouseY;
bMouse = true;
}

if (InputData.KeyMask || bMouse) {
TEvent InputEvent(INPUT_EVENT, this, "Action");

InputEvent.SetData(&InputData);
mpOwnerEntity->SetEvent(InputEvent);
}
else if (mbWasKeyPressed) {
mbWasKeyPressed = false;
TEvent InputEvent(INPUT_EVENT, this, "Action");

InputEvent.SetData(&InputData);
mpOwnerEntity->SetEvent(InputEvent);
}

// Check for number key's being pressed
// Check for user choosing weapon (number pad)
sf::Key::Code KeyDown = Utilities::CheckKeyRange(
Input, sf::Key::Num0, sf::Key::Num9);

if (KeyDown != sf::Key::Count)
{
std::stringstream ss;
ss << (uint32_t)(KeyDown - sf::Key::Num0);
std::string Filter = ss.str();

TEvent InputEvent(INPUT_EVENT, this,
Filter);

mpOwnerEntity->SetEvent(InputEvent);
}

}

/******************************************************************
*
* Cleanup - Cleanup any used resources
*
*******************************************************************/
void TInput::Cleanup()
{
printf("TInput::Cleanup\n");
}

/******************************************************************
*
* Initialize - Initialize all resources
*
*******************************************************************/
void TInput::Initialize()
{
TEvent AppEvent(EVENT_DATA_EVENT, this, "GetApp");
AppEvent.SetData(&mpApp);
TEntityManager::GetInstance()->SetEvent(AppEvent);

// register for a Frame Tick update
mpOwnerEntity->RegisterForEvent(TInput::OnFrameTick,
(void *)this,
FRAME_UPDATE_EVENT);
}


Starting at the bottom again, Initialize(), we set the event to get the main SFML RenderWindow, which generates the input. We also register to get notified of every tick.

The rest of the work is done in FrameTick(), where we check if any key is down, and check if the mouse moved. If so, we generate events saying so. If a button was down last time, but not now, we send an empty KeyMask Event.

Here's Player.h


class TPlayer : public TComponent
{
public:

TPlayer(uint32_t Speed);
~TPlayer();

/******************************************************************
*
* OnInput - Callback for handling Input events
*
*******************************************************************/
static void OnInput(TEvent &Event, void *pThis);

/******************************************************************
*
* OnInput - Callback for handling Input events
*
*******************************************************************/
void Input(TEvent &Event);

/******************************************************************
*
* OnEventData - Callback for getting the camera location
*
*******************************************************************/
static void OnEventData(TEvent &Event, void *pThis);

/******************************************************************
*
* OnEventData - Callback for getting the camera location
*
*******************************************************************/
void EventData(TEvent &Event);

protected:
virtual void Cleanup();
virtual void Initialize();

uint32_t mSpeed;
TPhysicalObject *mpOurPhysicalObj;

double mCenterX;
double mCenterY;

};

And the source code:


/******************************************************************
*
* TPlayer - Constructor, simple
*
*******************************************************************/
TPlayer::TPlayer(uint32_t Speed) :
TComponent(PLAYER_LOGIC_COMPONENT),
mSpeed(Speed)
{
mpOurPhysicalObj = NULL;
}

/******************************************************************
*
* ~TPlayer - DeConstructor
*
*******************************************************************/
TPlayer::~TPlayer()
{

}

/******************************************************************
*
* OnEventData - Callback for getting the player's location
*
*******************************************************************/
void TPlayer::OnEventData(TEvent &Event, void *pThis)
{
if (Event.GetFilter() == "PlayerLoc") {
TPlayer *pPlayer =
reinterpret_cast(pThis);

pPlayer->EventData(Event);
}
}

/******************************************************************
*
* OnEventData - Callback for getting the player's location
*
*******************************************************************/
void TPlayer::EventData(TEvent &Event)
{
*((TPhysicalObject **)Event.GetData()) = mpOurPhysicalObj;
}

/******************************************************************
*
* OnInput - Callback for handling Input events
*
*******************************************************************/
void TPlayer::OnInput(TEvent &Event, void *pThis)
{
// We don't care about the number keys, only movement here
if (Event.GetFilter() == "Action") {
TPlayer *pPlayer =
reinterpret_cast(pThis);

pPlayer->Input(Event);
}
}

/******************************************************************
*
* OnInput - Callback for handling Input events
*
*******************************************************************/
void TPlayer::Input(TEvent &Event)
{
TInput::TInputData *pInputData;

// if we don't have our physics component, get it
if (mpOurPhysicalObj == NULL) {
mpOurPhysicalObj = dynamic_cast(
mpOwnerEntity->GetComponent(PHYSICAL_OBJECT_COMPONENT));

if (mpOurPhysicalObj == NULL) {
printf("Player Object with no Physical Object! ABORT ABORT!!\n");
}
}
pInputData = ((TInput::TInputData *)Event.GetData());

cpFloat xForce = 0, yForce = 0;
cpVect Vel;
bool bChangeVelocity = false;

mpOurPhysicalObj->GetVelocity(Vel);

// We'll just assign velocities to a hardcoded value for now
if (pInputData->KeyMask & (1 << (uint32_t)GAME_KEY_LEFT))
xForce -= mSpeed*20;
else if (Vel.x < -0.01f) {
Vel.x = 0;
bChangeVelocity = true;
}

if (pInputData->KeyMask & (1 << (uint32_t)GAME_KEY_RIGHT))
xForce += mSpeed*20;
else if (Vel.x > 0.01f) {
Vel.x = 0;
bChangeVelocity = true;
}

if (pInputData->KeyMask & (1 << (uint32_t)GAME_KEY_DOWN))
yForce += mSpeed*20;
else if (Vel.y > 0.01f) {
Vel.y = 0;
bChangeVelocity = true;
}

if (pInputData->KeyMask & (1 << (uint32_t)GAME_KEY_UP))
yForce -= mSpeed*20;
else if (Vel.y < -0.01f) {
Vel.y = 0;
bChangeVelocity = true;
}

if (bChangeVelocity) {
mpOurPhysicalObj->SetVelocity(Vel);
}

mpOurPhysicalObj->SetForce(cpv(xForce, yForce));

// Finally, find location of Mouse and point player towards it
cpFloat MouseX = (cpFloat)pInputData->MouseX;
cpFloat MouseY = (cpFloat)pInputData->MouseY;

cpFloat Angle = atan2(MouseY - mCenterY,
MouseX - mCenterX);
mpOurPhysicalObj->SetAngle(Angle);

}

/******************************************************************
*
* Cleanup - Cleanup any used resources
*
*******************************************************************/
void TPlayer::Cleanup()
{
printf("TPlayerCleanup\n");

}

/******************************************************************
*
* Initialize - Initialize all resources
*
*******************************************************************/
void TPlayer::Initialize()
{
// Get the render window so w know where center is
sf::RenderWindow *pApp;
TEvent AppEvent(EVENT_DATA_EVENT, this, "GetApp");
AppEvent.SetData(&pApp);
TEntityManager::GetInstance()->SetEvent(AppEvent);

mCenterX = (double)(pApp->GetWidth()/2);
mCenterY = (double)(pApp->GetHeight()/2);

// We want to get the message for our location from entity manager
mpOwnerEntity->RegisterForEvent(TPlayer::OnInput,
(void *)this,
INPUT_EVENT);

mpOurPhysicalObj = dynamic_cast(
mpOwnerEntity->GetComponent(PHYSICAL_OBJECT_COMPONENT));

if (mpOurPhysicalObj == NULL) {
printf("TPlayer Object with no Physical Object! ABORT ABORT!!\n");
}

// We want to get the message for our location from entity manager
TEntityManager::GetInstance()->RegisterForEvent(TPlayer::OnEventData,
(void *)this,
EVENT_DATA_EVENT, mpOwnerEntity);

// Register for sounds on certain events
TSound *pSound = dynamic_cast(
mpOwnerEntity->GetComponent(SOUND_COMPONENT));
if (pSound == NULL) {
printf("TPlayer Object with no pSound! ABORT ABORT!!\n");
}

pSound->RegisterSound("PlayerHit", COLLISION_EVENT,
"Bullet");
pSound->RegisterSound("Armor", COLLISION_EVENT,
"Armor");
pSound->RegisterSound("Weapon", COLLISION_EVENT,
"Weapon");
pSound->RegisterSound("PlayerDead", DEATH_EVENT,
mpOwnerEntity->GetType());

}


The constructor takes the speed the player moves. The 2 main things the Player component does is gets input events, and, if it's a direction event, it gives a force to the entity's PhysicalObject. If there's a mouse movement, it gives an angle to the PhysicalObject. (Notice, it doesn't handle firing bullet, that's all done by Weaponry).
It also handles events from other people wanting to know where the player is.

Finally, it tells the Sound component to play certain sounds on certain Events.

Next time we'll finish off the Component System talk when I detail how we put it all together to make the SmashPC game.

1
Sign in to follow this  
Followers 0


2 Comments


dejaime,

It's my own implementation. Check out [url="http://www.gamedev.net/blog/1385/entry-2253941-my-component-base-entity-system-part-1/"]My Component Based Entity System Part 1[/url] the 2nd post of this blog. Specifically, check the TEvent.h and .cpp, and TEntity.cpp code, where I show how we handle RegisterForEvent(), and SetEvent().

As I mentioned earlier, I'm using strings as Event filters (after etEventType), which I know is not the most efficient, but, currently, I'm not seeing a performance hit, so I'm leaving it as is.
0

Share this comment


Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now