Finding which Block Clicked
#1 Members - Reputation: 138
Posted 28 November 2011 - 07:40 PM
I'm using Java and Slick2D.
#2 Marketplace Seller - Reputation: 8941
Posted 28 November 2011 - 09:29 PM
Example:
Block = (MousePos + CameraPos) / BlockSize;
Block is the cell that a block may or may not be in. You can usually use this to get the index into your array of blocks, if you have one, with something like this:
Index = (Block.y * NumBlocksWide) + Block.x;
(If your blocks are stored that way in memory).
CameraPos is the location of the camera (usually the upper-left corner of the screen) in the game world, in pixels. MousePos is the location, in pixels, relative to the upper-left of the screen (which is why MousePos + CameraPos equals the position of the mouse in the game world). BlockSize is the constant size of the grid cells of your world.l
This is assuming you are using a grid-based system for blocks. If not, you can partition your game world into chunks, and have a list of objects in each chunk, and then only check if the mouse is in the bounding box of any object in that chunk.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal
#3 Members - Reputation: 138
Posted 29 November 2011 - 02:51 PM
How are you drawing the blocks? Use the same positioning you use to draw the blocks to get their physical location in the game world, and calculate the location of the mouse in the game world.
Example:
Block = (MousePos + CameraPos) / BlockSize;
Block is the cell that a block may or may not be in. You can usually use this to get the index into your array of blocks, if you have one, with something like this:
Index = (Block.y * NumBlocksWide) + Block.x;
(If your blocks are stored that way in memory).
CameraPos is the location of the camera (usually the upper-left corner of the screen) in the game world, in pixels. MousePos is the location, in pixels, relative to the upper-left of the screen (which is why MousePos + CameraPos equals the position of the mouse in the game world). BlockSize is the constant size of the grid cells of your world.l
This is assuming you are using a grid-based system for blocks. If not, you can partition your game world into chunks, and have a list of objects in each chunk, and then only check if the mouse is in the bounding box of any object in that chunk.
Yeah, I can't believe how simple this solution is. I completely forgot.






