Okay so this might be long since I have the program separated into multiple files, but I want to know if I'm doing this the "right" way before going any further.. if you don't understand something, please ask! I tried to make this minimal to get the point across, although it's still pretty long :/
I made this basic example of a Game program.
The Game class has:
- a player property
- a float x property
- an update function.
The Player class has an update function as well.
The Game class's update function calls the player's update function. This is to organize my code better for when the game gets bigger, encapsulation and all that...
The problem I was having is that the
Player::update function needs to access a property of the Game class that the player belongs to. Otherwise, the player has no idea how to update itself based on the "x" property of the Game class.
The way I figured out how to do this is to have the Game class pass its dereferenced
this pointer to the Player's update function.
Code (not the actual game I'm working with, but it shows the same issue:
main.cpp
1 2 3 4 5 6 7 8
|
#include "Game.h"
int main()
{
Game game;
game.update();
return 0;
}
|
Game.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#ifndef GAME_H
#define GAME_H
#include "Player.h"
//class Player;
class Game {
public:
Game();
float getX() const;
void update();
private:
float deltaTime;
float x;
Player player;
};
#endif // GAME_H
|
game.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include "Game.h"
#include "Player.h"
Game::Game()
: deltaTime(0.1f)
, x(42.f)
, player()
{}
float Game::getX() const
{return x;}
void Game::update()
{
for (int i = 0; i < 10; i++)
//calls its dereferenced self:
player.update(deltaTime, *this);
}
|
Player.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#ifndef PLAYER_H
#define PLAYER_H
#include "Game.h"
class Game;
class Player {
public:
Player();
void update(float deltaTime, Game game);
private:
static const float Speed;
float pos;
};
#endif // PLAYER_H
|
player.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
#include "Game.h"
#include "Player.h"
const float Player::Speed = 10.f;
Player::Player()
: pos(100.0f)
{}
void Player::update(float deltaTime, Game game)
{
pos += Speed * deltaTime;
pos += game.getX(); //The point of this is to use a property from the game.
std::cout << pos << std::endl;
}
|
I'm probably not using the right term, I think it's aggregate. Basically, I am just wondering if this (by having a dereferenced Game as a passed function parameter) is the best way to make it so the Player::update() function can have access to the Game's properties.
Is there a better way to do this?
-------------------
tl;dr:
1 2 3 4 5 6 7
|
Game class:
-Player object member
-x variable
-update() {call Player's update, update other things...}
Player class:
-update() {needs access to Game's x variable, don't know the best way to do this}
|