I think this is a fairly easy thing to implement but I just want the ghost to begin moving one space at a time toward the player, if the player is within 5 spaces of the ghost. In my if statement in move_to_x_y is where the change should be added. How can I do the if statement to move depending on where the player is?
Here is the function checking to see if the ghost is within five spaces:
bool Game::nearby (Ghost & ghost) const
{
if (abs(m_player->get_x() - ghost.get_x()) < 5)
return true;
if (abs(m_player->get_y() - ghost.get_y()) < 5)
return true;
return false;
}
Then here is the ghost's move function, he usually just moves in a random direction, which is the else case for when the player is not within five spaces:
void Ghost::move (Game & game) {
Floor * floor;
int r;
bool moved = false;
floor = game.get_curr_floor();
do
{
if (game.nearby(*this))
r = //WHAT TO ADD HERE???
else {
r = rand() % 4;
switch (r)
{
case 0:
moved = floor->move_to_x_y (game, *this, 1, 0);
break;
case 1:
moved = floor->move_to_x_y (game, *this, 0, -1);
break;
case 2:
moved = floor->move_to_x_y(game, *this, -1, 0);
break;
case 3:
moved = floor->move_to_x_y(game, *this, 0, 1);
break;
}
}
}
while (! moved);
}
So depending on where the player is, either move up, down, left or right, toward them.
Thanks for the help!
Your function returns whether or not the player is nearby, but gives no information as to which direction the player is in. Change the return value from a bool to an int, or something to indicate the direction. For example:
int Game::nearby (Ghost & ghost) const
{
if (ghost.get_x() - m_player->get_x() < 5 && ghost.get_x() - m_player->get_x() > 0)
return 2;
if (m_player->get_x() - ghost.get_x() < 5 && m_player->get_x() - ghost.get_x() > 0)
return 0;
if (ghost.get_y() - m_player->get_y() < 5 && ghost.get_y() - m_player->get_y() > 0)
return 3;
if (m_player->get_y() - ghost.get_y() < 5 && m_player->get_y() - ghost.get_y() > 0)
return 1;
return -1;
}
This will return the number that already corresponds to the direction you want him to move in your switch statement. So all you have to do in your move function is set r to the int "nearby" returns, and if it returns -1, set it to a random direction as before.
r = game.nearby(*this);
if (r == -1)
r = rand() % 4;
switch (r) .... etc