I'm programming an isometric game in Java, but I stuck when I wanted to get the tile, where the mouse pointing.
Is there a way, to calculate it?
here is the code for rendering
int posX = 10;
int posY = 0;
static int beginY = 500-72;
static int beginX = 800-36;
static int newLineY = 60;
static int newLineX = 200;
posY = ((0+1)*9)-9+beginY/2;
posX = ((beginX)/2)+18-(18*(0+1));
for (int y = 0; y <= world.length-1; y++) {
for (int x = 0; x <= world[y].length-1; x++) {
if (world[y][x] == 1) {
g.drawImage(grass, posX, posY, null);
posX += 18;
posY += 9;
} else if (world[y][x] == 2) {
g.drawImage(wall, posX, posY-38, null);
posX += 18;
posY += 9;
} else if (world[y][x] == 3) {
g.drawImage(stone, posX, posY, null);
posX += 18;
posY += 9;
} else if (world[y][x] == 4) {
g.drawImage(water, posX, posY, null);
posX += 18;
posY += 9;
} else {
posX += 18;
posY += 9;
}
if ((y-pPosX) * (y-pPosX) + (x-pPosY) * (x-pPosY) <= 3*3 && world[y][x] != 0 && world[y][x] != 2 && world[y][x] != 4) {
g.drawImage(hollow, posX-18, posY-9, null);
}
if (y == selectedX && x == selectedY) {
g.drawImage(selected, posX-18, posY-9, null);
}
if (world2[y][x] == 9) {
g.drawImage(character, posX-18, posY-53, null);
}
}
posY = ((y+1)*9)+beginY/2;
posX = ((beginX)/2)-(18*(y+1));
}
This is the result. beginX
and beginY
start at the top corner of the diamond:
First register a MouseListener to your panel (the panel where you want to draw your tiles). Now, according to your rendering code you actually "know" where each tile starts. So all you have to do is calculate which tile was clicked.
JPanel gamePanel = new JPanel();
gamePanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
int x=event.getX();
int y=event.getY();
System.out.println("clicked at ("+x+","+y+")"); //these co-ords are relative to the your gamePanel
}
});
EDIT:
I changed to code above, it wasn't correct. But I am sure you'll figure it out. So above code shows you how to add a MouseListener
to your panel/frame. And if it works, you should be able to see in the console where you click.
Now you only have to calculate which tile was clicked:
(x,y) --> + - - -
' /\
' / \
'/ \
\ /
\ /
\/ + <-- (x+36, y+18)
your mouse pointer needs to be somewhere between the two points (x,y)
and (x+36, y+18)
. Of course there is the additional problem that someone could click somewhere between (x,y) and (y+36, y+18) but still not click on the tile (maybe someone clicks on the tile top left of it) and there you may need to decide which tile you want to be selected.
Another way would be to divide your panel into a panel of squares. But without drawing them of course. Imagine that each tile could have a square in the middle:
/\
/____\
/ | | \
\ |____| /
\ /
\/
something like that. so you only need to calculate if someone clicked inside the square.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments