1

i have ran into a quick problem which i do not know how to do it by myself but i'm sure with your help i will understand more.

I've created a level editor for the game engine i am creating and i am trying to make the mouse position snap to a 32x32(grid) or 64x64(grid) so that the tiles are placed correctly and not overlapping each other.

So that its not like this : https://i.stack.imgur.com/uL60U.jpg but more like this : http://imgur.com/a/nck9N Sorry for the really bad explanation.

The mouse position code i am using is

public int getMouseX() {
    return mouseX; // Get MouseX
}


public int getMouseY() {
    return mouseY; // Get Mouse Y
}

public void mouseMoved(MouseEvent e) {
    mouseX = (int)(e.getX() / gc.getScale() /*+  gc.getWindow().getFrame().get*/);
    mouseY = (int)(e.getY() / gc.getScale()); //CODE TO GET MOUSE X AND Y


}

//Code Which Loads the texture/image where the mouse is

tMouseX = gc.getInput().getMouseX() -32;
tMouseY = gc.getInput().getMouseY() - 32;
putImage((int)tMouseX,(int)tMouseY,r);

//putImage Function

public void putImage(int x, int y)
{
    objects.add(new Grass(x,y));

}

Trying to make the images snap to 32x32

NightX
  • 47
  • 7
  • Did you write any code for the snapping you want to achieve? – luk2302 Jun 10 '17 at 15:28
  • You've forgotten to ask a clear question -- what problems are you having? What is broken? – Hovercraft Full Of Eels Jun 10 '17 at 15:28
  • Added some pictures and @luk2302 i do not know how to code this snapping. – NightX Jun 10 '17 at 15:30
  • So the question is "how to snap to grid"? Please post a small [mcve] program so we have code that we can work with. This is not your whole program nor code snippets but a small representational new program that is small enough to post here as code-formatted text, and that will compile and run for us without modification. – Hovercraft Full Of Eels Jun 10 '17 at 15:32
  • Yes its how to snap to grid and ill try to post a small minimal complete and verifiable example – NightX Jun 10 '17 at 15:39

1 Answers1

0

Don't worry about snapping the mouse to the grid, you don't really want to do that. What you want is to snap the tile to the grid.

The best way to do this is with integer division. Divide by your tile size using integers to truncate the remainder (or use floor) and then scale back up by multiplying by your tile size.

int tilepos_x = (int)(mousex / tileSize) * tileSize;
int tilepos_y = (int)(mousey / tileSize) * tileSize;
James Poag
  • 2,320
  • 1
  • 13
  • 20