C ++ game development and polymorphism

I'm trying to implement some kind of "game engine" just for me ", and the plot of the problem is as follows:

Suppose I have an abstract interface for a rendered object, for example. IRenderable.

And it is declared as follows:

interface IRenderable {
  // (...)
  // Suppose that Backend is some abstract backend used
  // for rendering, and it implementation is not important
  virtual void Render(Backend& backend) = 0;
};

What I'm doing now is something like declaring different classes, such as

class Ball : public IRenderable {

  virtual void Render(Backend& backend) {
    // Rendering implementation, that is specific for
    // the Ball object
    // (...)
  }
};

And then everything looks good. I can easily do something like std::vector<IRenderable*> items, click elements like in it new Ball(), and then make a call that looks likeforeach (IRenderable* in items) { item->Render(backend); }

Well, I think this is a "polymorphic" way, but what if I want to have different types of objects in my game and the ability to manipulate their state, where each object can be controlled through its own interface?

I could do something like

struct GameState {
  Ball ball;
  Bonus bonus;
  // (...)
};

, ball.Move(...) bonus.Activate(...), Move(...) Ball Activate(...) - Bonus.

foreach IRenderable* , , .

ball.Render(backend);
bonus.Render(backend);
// (...)

, ( Render ..

downcasting dynamic_cast - typeid, , , , "" .

, : - () , , - , IRenderable* ( Render ), ?

, - , , :)

!

+3
3

++, , , ...

Renderable Render

Movable Renderable, , x, y, z Move

Ball Movable

Renderable , Render, .

, , , Moveable, .

( ), Collectable, Moveable.

+1

, , IRenderable*.

struct GameState {
  Ball ball;
  Bonus bonus;
  vector<IRenderable*> m_items;

  GameState() // constructor
  {
    m_items.push_back(&ball);
    m_items.push_back(&bonus);
  }

};

, , m_items. GameState.

, foreach .

+3

. . . .

Now you can easily have objects that have state, but cannot be displayed, and so on. Perhaps you may have a separate subsystem for audio. It should also help keep your code clean and modular.

+2
source

Source: https://habr.com/ru/post/1742367/


All Articles