I am trying to update the text rendered on the screen after the health of a player changes. The problem I am having is deciding where to update this. The player and health graphics are separate objects.

Currently,my code is organized like this: The main c++ has vectors:

  • vector< Players>
  • vector< Renderables>

"Renderables" is anything that can be rendered. It has a member function render() which is called for every object in the vector. A "Text" class inherits from it. It contains the string that is displayed on screen. "Text" has its own render function, and calls its member function getString() inside its render function.

The question is where do I update this string once the player's health has changed?

My current solution is actually to have a "PlayerHealth" subclass of "Text", which holds a pointer to the player. That way "PlayerHealth"can just redefine getString() as player->health converted to a string, and using "Text"'s render function. But I've been told this wasn't a very good method and was wondering what other approaches there were to this problem.

Thank you for your time


Fundamentally, you need to create some kind of association between a Player and the possibly-many sets of Text associated with that player. When you have that association, you can (depending on how you implement the association):

  • push the new player health text to the correct Text from the Player or
  • pull the new player text from the Player in the Text

There are several ways to establish this link; subclassing Text and creating a PlayerHealth that refers to a Player is on one way, but it doesn't scale well. You'll end up having to create lots of little subclass's, potentially, creating a maintainability problem.

A better option might be to give the Player a set of pointers to Text objects associated with the player in various ways. Perhaps they need a pointer to the Text representing their health, and one for their name, maybe one for debug information like position in the world, et cetera.

This allows you to easily push text updates from the Player, but doesn't really require any management of the Text on the player's part (except to know Text exists), so you preserve the separation you have.

A more general approach that's very common these days is to go for a full-on "component-based entity system" (or "ECS") and represent the player as a generic entity object with various components, such as components for each associated text. This option is more generic and puts more of an abstraction buffer between the two systems (potentially), but is also more work to implement and can be a source for design analysis paralysis. So if you go that route remember to focus on your concrete goals.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.