So I am making a pacman-like game. the game has tiles/grid. I keep the node data in a struct:

struct Node

    std::pair <int, int> node; // position of the node <x,y>
    float f = 0,
          h = 0,
          g = 0;
    std::pair <int, int> previous; 
    bool iswall = false;
    sf::Vector2f rectCenter = sf::Vector2f(0, 0);
    sf::Vector2f position;


i use the struct to calculate a path, check if the cell is an obstacle (or not) etc.

now in the main I use the arrays and a for loop to draw the grid:

for (int i = 0; i<col; i++)
        for (int j = 0; j < row; j++)
            /*default color is black*/
            box[i][j].setSize(sf::Vector2f(w, h));  
            box[i][j].setPosition(sf::Vector2f(i*w, j*h));
            sf::FloatRect fbox = box[i][j].getGlobalBounds();

[enter image description here1

I also use the strcut to create specific nodes (current position, start node, end node)

and i draw it in the man like this:

        //displays the start node as green
        if (i == crntNodex && j == crntNodey)

now the problem that I'm facing is making a function that can get the current node that the player (blue square on the green cell) is. My attempt for this was checking if the cell contained the player

std::pair<int, int> AIEnemy::getNodePosition(sf::RectangleShape * grid, int i, int j)

    if (box.contains(rect.getPosition().x, rect.getPosition().y))
         return std::pair<int, int>(i,j);

but It is not efficient (and also doesn't update). is there a way I can get game objects coord on a grid?


1 Answer 1


If your player is at (x, y) where both coordinates are in pixels, and you know that the width pf a tile is w pixels, then you can get the position by simply doing

posX = floor(x / w)
posY = floor(y / w)
  • \$\begingroup\$ thank you very much for the response it works. and if anybody else is seeing this for posY its posY = floor(y / h) \$\endgroup\$ Commented Mar 20, 2019 at 0:04
  • \$\begingroup\$ @YamaraiAkizuki if the answer solved your problem, press the tick button \$\endgroup\$
    – Bálint
    Commented Mar 20, 2019 at 1:14
  • \$\begingroup\$ sorry still getting used to this \$\endgroup\$ Commented Mar 21, 2019 at 18:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .