• Advertisement
Sign in to follow this  

component GameObject mechanism

This topic is 4689 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi guys, I came up with the following mechanism last night. I figured I would put it out here for whoever wants to use it. The design idea was to have everything stored as code - as in, all game objects compiled in C++ code, not script. If someone out there finds a use for this - great! Good luck.
#include<iostream>
using std::cout;
using std::endl;


template< typename _Ct>
class IComponent
{
public:
	virtual _Ct* GetComponent() { return 0; }
};

namespace Component
{
	class Lock : public virtual IComponent< Lock>
	{
		Lock* GetComponent() { return this; }

	public:
		bool locked;

	};

	class Open : public virtual IComponent< Open>
	{
		Open* GetComponent() { return this; }

	public:
		bool open;
	};
}


class GameObject :
	//note - GameObject must inherit from all templated component types, as such:
	private virtual IComponent< Component::Lock>,
	private virtual IComponent< Component::Open>
{
public:
	template< typename CompType> CompType* Get() { return static_cast< IComponent< CompType>*>( this )->GetComponent(); }

};


//these would be actual game objects
class Door: public GameObject, public Component::Open
{
};


class Chest: public GameObject, public Component::Lock, public Component::Open
{
};


int main()
{
	using Component::Lock;
	using Component::Open;


	GameObject* door = new Door;
	GameObject* chest = new Chest;


	Lock* chest_lock = chest->Get< Component::Lock>();
	Open* chest_open = chest->Get< Component::Open>();

	if( chest_lock )
	{
		cout << "Yep.\n";
		chest_lock->locked = true;
	}
	else cout << "Nope.\n";

	if( chest_open )
	{
		cout << "Yep.\n";
		chest_open->open = true;
	}
	else cout << "Nope.\n";


	Lock* door_lock = door->Get< Component::Lock>();
	Open* door_open = door->Get< Component::Open>();

	if( door_lock )
	{
		cout << "Yep.\n";
		door_lock->locked = true;
	}
	else cout << "Nope.\n";

	if( door_open )
	{
		cout << "Yep.\n";
		door_open->open = true;
	}
	else cout << "Nope.\n";



	delete chest;
	delete door;
}

Share this post


Link to post
Share on other sites
Advertisement
Sign in to follow this  

  • Advertisement