Win a copy of Raising Young Coders: A Parent’s Guide to Teaching Programming at Home this week in the General Computing forum!
Forums Login/signup

Snapping a value to a 48x48 grid

+Pie Number of slices to send: Send
I'm making a tower defence video game and I want to capture the mouse x and mouse y to figure out which tile he is mousing over. My tiles are 48x48, so i used this to get the tile (x=0,y=1 in "tile space" means x=0, y=48 in "normal/mouse space"):


This works excellently for the x but using the same formula for the y results in only the top half of the tile being clickable and the bottom half gets mapped to the tile 1 space lower()

My source code is at this address
+Pie Number of slices to send: Send
Update: I found that tilePos = pos/72 works, but I can't find any relation between 48 and 72 I think the pos returned by MouseEvent.getY() include the bar on top of the window

1
+Pie Number of slices to send: Send
I have fixed it. My speculation is correct. I measured the height of the top bar(27px) and subtracted it from the mouseY. I did this on my mac and also confirmed that it works on Windows(25).

I also googled it and found that there is a method in JFrame called getInset() which tell me the height of the JFrame consumed by the title bar. I can then subtract this from the MouseY to get the actual mouseY.
+Pie Number of slices to send: Send
if you actually make a 48x48 grid, with each tile as in independent object, then you can use the mouse over to identify which object you are actually hovering over or which object you are doing actions with--provided each has a common mouse listener (at least much easier).

reply
reply
This thread has been viewed 3111 times.
Similar Threads
2D Camera tracking Player
Creating a game with your idea
Multiple mouselisteners
Collision detection
I wrote a 2048 clone, looking for feedback
More...

All times above are in ranch (not your local) time.
The current ranch time is
Jun 27, 2025 04:05:20.