Search code examples
javagame-enginetiles-game

Java, Level Editor Issue


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.sstatic.net/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


Solution

  • 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;