Reputation: 597
I have two classes, Player and Controller. The Controller has the main game loop, and contains a Player. It also stores the world map. The Controller class passes user input to the player by calling various methods of the Player class, such as moveForward(). I am now implementing collision detection, and to do so, I need a way for the Player class to see the world map, but this is in the Controller class in which the Player class is.
In other words:
struct Controller {
int worldMap[16][16][16];
Player p;
...
}
struct Player {
movePlayer() {
#How do I check world map here?
}
}
Upvotes: 0
Views: 85
Reputation: 42828
Pass the data that movePlayer()
needs as a reference parameter:
void movePlayer(const int (&map)[16][16][16]) { ... }
Passing the whole Controller
object would be bad if movePlayer()
only needs access to worldMap
.
Alternatively, you could store a pointer to the current map in the Player
object itself:
struct Player {
// ...
private:
int* Location;
};
Upvotes: 0
Reputation: 85
Since you are propably accessing the controller a lot, you can pass in a pointer to the Player
and there you assign it to a member.
struct Controller {
int worldMap[16][16][16];
Player p;
...
Controller() {
p.setController( this );
}
};
struct Player {
Controller* mController;
movePlayer() {
mController->...
}
setController( Controller* controller ) {
mController = controller;
}
};
If you need access to it at a low interval, you can pass a reference into the function.
Player::movePlayer( Controller* controller ) {
mController->...
}
Upvotes: 1
Reputation: 11116
For simplicity let us assume that all you want to do is call a simple function (checking the other member works the same way but leads to more complicated examples):
void move(Player&);
You can only access non-static
members if you have an object at hand. If you do, it is as simple as:
struct Player {
void movePlayer(Controller& controller) {
move(controller.p);
}
};
Note the ;
following the struct
declaration, it is required.
If you have static
members on the other hand they are valid for the whole class and thus don't even need an object:
struct Player {
void movePlayer();
};
struct Controller {
static Player p;
};
void Player::movePlayer() {
move(Controller::p);
}
Note the order in which the declarations appear: To declare a variable of type Player
, you need to first declare the struct Player
.
Upvotes: 1