Followers 0

[Design Question] How to access other classes

6 posts in this topic

Hello.

I think the best way is to start with an example of my problem. I made a little game with diffrent objects. Each object interacts with the others and access them. (Like if a bullet hits a enemy, it destroys the enemy). So maybe you would put all this code in the Game-function()-Method.

I read somewhere that each object should update itself. So i made a Update()-function for every class.

Example:

I got a Ball-Class that checks in his Update()-Function if it collides with the player or other game objects. If the ball touches the lower border, the players lifes are decreased.

The Question:

How do i realise that? I first thought of giving the player each game-loop through the update-function. That wasn't that clean. So i changed the Ball Class

Ball::Ball( Player *player, posX, ....

Now i could access the player in the Update()-function to change its values. But i dont know if this is good practise. One big thing is, that i dont only have to access the player, but nearly every object in the game.

Here is an example of my Ball Class-Structure:

class Ball :
public cEntity
{
private:
double	m_VelX;
double	m_VelY;
double	m_Speed;
bool	m_Super;
Player* m_Player;
vector<Ufo*> *m_Ufos;
vector<PowerUp*> *m_PowerUps;
cAnimationManager *m_AnimationManager;
cSound	*m_Sound;
public:
Ball(cGraphics *graphics, cAnimationManager *animManager, cSound *sound, Player *player, vector<Ufo*> *ufos, vector<PowerUp*> *powerups, string texture, int posX, int posY, int width, int height);
~Ball();

void Update( double delta );
void CheckCollision();
void Draw();
void Reset();



Should i continue this way?

Thanks,

Daniel

Edited by Agreon
0

Share on other sites

My advice' try to implement a game object-component system. A GO is just an entity that encapsulates components and components are for behaviors.

Then you can store in a list all components attached to the go and then have a GetComponent method that iterate through the list to find the component you passed as parameter.

If your case since you are comparing your object with all others for collision, you would have the GO reference, if you get a collision using the go you can find any other components you would want to access.

Each game object you create would inherits from GameObject class which contains all need methods and the protected list of components. Any behavior inherits from component and can be added to the list.

EDIT: The least when someone downvotes an answer is to have the guts (or balls) to expose why you consider it deserves. I do not see why this is a candidate for downvote since it is the pattern, engines are opting for, like Unity3D for instance. So except if you (whoever you are) can prove that Unity is a joke in the way they implemented their engine I would consider this answer a potential help to the OP.

Note I do not care about reputation as it does not pay the bills. So feel free to downvote some more as long as you let me know why.

Edited by fafase
0

Share on other sites

It's not that what you're offering is bad fafase, you're just trying to get a BEGINNER to do what's used in systems as complex as Unity.. No need to over complicate. (I didn't down-vote you, just offering my thoughts!)

Personally, Agreon, I'd do what I've seen for years - have a Game class that handles all of this for you. What you're doing is fine.. But if everything had a pointer to everything else it nigh on defeats the purpose of OOP!

Game class:

Holds a pointer to a player
Holds pointerS to multiple balls

Player and ball hold nothing regarding each other. However, I'd recommend adding a function for Ball that checks whether it collides. You can do that by passing a pointer in a function:

bool Ball::CollidesWithPlayer(Player* pPlayer)
{
// Do math checks, return true if it does, false if not
}

Inside your game class, you can then do whatever action you want to. Reset the level, deduct lives etc. Alternatively have a player function that takes a pointer to a Ball and does the same check, then in Game::Update you can just iterate across all your balls and check. Actually you can do that in either scenario..

Hope this helps!

0

Share on other sites

Thank you for your suggesstion, but let's say i have a game with many entities; That would be very confused in the game class.

0

Share on other sites

You will have to keep a list of all game entities somewhere, so processed entities can look them up and (non ideally) access them themselves. There is no other way. Use an abstract entity class to reference all different entity types and to encapsulate basic functionality shared between all of them. You can use messaging in a simple form of virtual methods to handle different entity types. This is how I would do it while keeping your simple entity structure (no systems, no components, etc.).

// Could be global or passed to every entity as a pointer.
// Use smart pointers to hold entities instead.
std::list<Entity*> entities;

// Base entity class.
class Entity
{
/* ... */

public:
void Update(float delta)
{
this->CheckCollisions();
this->OnUpdate(delta);
}

virtual void Draw()
{
// Drawing can be done in many ways.
}

void CheckCollision()
{
for(/* every entity on the list, but yourself */)
{
?            if(/* check if collides */)
{
this->OnCollision(other);
}
}
}

void Damage(int damage)
{
// Substract damage from health and call Destroy() if it's below zero.
/* ... */

// Message itself about being damaged.
this->OnDamage(damage);
}

void Destroy()
{
// Mark as dead, but don't remove from the list yet.
/* ... */

// Message itself about being destroyed.
this->OnDestroy();
}

private:
virtual void OnUpdate(float delta) { }
virtual void OnCollision(Entity* other) { }
virtual void OnDamage(int damage) { }
virtual void OnDestroy() { }

private:
Enum type; // Player or a ball?

bool alive;
float position_x;
float position_y;
int health;
}

// Player entity class.
class Player : public Entity
{
/* ... */

public:
void Draw()
{
// Draw a player on the screen.
}

private:
void OnUpdate(float delta)
{
// Control the player entity.
// And fire bullets!
}

void OnDamage(int damage)
{
// Flash on damage.
}

void OnDestroy()
{
// Create an explosion (by creating a new entity?).
}
}

// Bullet entity class.
class Bullet : public Entity
{
/* ... */

public:
void Draw()
{
// Draw a bullet on the screen.
}

private:
void OnUpdate(float delta)
{
// Move the bullet forward.
}

void OnCollision(Entity* other)
{
// Check if we collided with the player.
// Could be done via RTTI.
if(other->GetType() == ENTITY_PLAYER)
{
// Damage the player entity for 10 HP.
other->Damage(10);

// Destroy itself.
this->Destroy();
}
}
}

// Create entities.
// It's sometimes useful to save a pointer to the player's entity so it can be quickly retrieved.
entities.push_back(new Player(/* ... */));
entities.push_back(new Bullet(/* ... */));

// Main loop.
while(true)
{
/* ... */

for(/* every entity */)
{
entity->Update(delta);
entity->Draw();
}

for(/* every entity */)
{
// Remove dead entities from the list.
}
}


Edit: If you don't want to hold a pointer to the player, you will have to go a bit beyond this. Create a system that will let you tag or name an entity as a "player", so you can later retrieve it without manually holding a pointer to it. Example:

// At entity creation.
Entity* entity = new Player();

entitySystem->TagEntity(entity, "player"));

// Anywhere else.
Entity* player = entitySystem->GetEntityByName("player");

Edited by Guns
2

Share on other sites

I read somewhere that each object should update itself. So i made a Update()-function for every class.
Maybe this is what is written, but I doubt it is what it's intended.

Personally, I'm starting to hate the word components and component based system, as many discussions about them end up being very high level and seldom useful. Many of their subtle problems are also rarely even taken in consideration, let alone discussed.

Anyway, your objects should not update themselves. That is, they should not have an Update call. Ideally.

Seconding Guns, and hopefully elaborating on the approach.

The Update call was basically an hack introduced to allow finer degree of flexibility, often going along with scripting. It suffers from being overly generic and if you look at systems using them, you'll notice there has been a growth of Update calls. Before rendering. Before physics. After everything.

Consider using this (anti?)pattern as a last resource.

Now, I see you're currently doing the physics yourself so you can manipulate speed and velocity. This is model data. There are also data related to presentation (m_Sound, m_AnimationManager) and stuff regarding gameplay-level model (powerups?). So your Ball is really a fusion of at least three different structures.

What it lacks is separation of concerns.

Let's pass the fact you're doing physics yourself (which is possibly appropriate for this kind of game). What you really want to have is a higher-level system keeping a list of collidable objects and dispatching calls appropriately, something like:

1. Collision system build a collision list
2. Gameplay system searches for the ball in the collision lists
3. For each match, searches for the kind of hit object
1. Is it an UFO? Call ufo->destroy, player->addPoints, signal ball bounce/collision/nothing
2. Is it a powerup? Call powerup->remove, player->applyPowerup, ball->applyPowerup
3. Otherwise, ball->collision.

In this way your Ball becomes a much smaller structure. It has a much more limited goal and knowledge. By delegating part of the low-level behavior to other components you get to avoid big god objects. For example, it does not need to have access to ufos or powerups anymore but only to react to them when informed.

Proponents of the component-entity model decided that this approach had to be glorified by giving it a sticker.

2

Share on other sites

I usually have a World class that contains all entities in the game. In this case, a World might have a Player, and some Ball. This World class has a list of all entities, and each entity is identified by an id. For example, player's id is 0, and the first ball's id is 1, etc. Each entity also keeps reference to this World class.

I usually make each entity update themselves for every tick of the game, but their update functions are called from the World class in its own update function. On every tick of the game loop, the World's update function is called, which loops through all entities, calling their update function one by one. The update function for Player might be recalculating its position and draws itself on the screen according to the new position. The update function for Ball might be changing its direction randomly and checks if it meets the Player by referencing the World class. It needs to draw itself on the screen too. Every entity needs to draw themselves according to their position, so it's not a bad idea to have a render function in the class. Well, the render function is likely to be similar (printing the sprite on the coordinate), so I think it wouldn't hurt to make a parent Entity class for Player and Ball.

That's how I usually code my games. I'm not sure why Krohm said that objects shouldn't update themselves, but you better listen to him. I'm still learning myself.

0

Create an account

Register a new account