Skip to main content
GameDev.net gamedev.net
🔒 Locked

Select a cell in a grid

Started by tuppe99 Apr 18, 2008 at 3:47 PM 0 replies 950+ views
Original Post
tuppe99
tuppe99
My 10 year old son wants me to write a game with and since I am not very experienced in the area,I would like to have some algorithm advice if anybody can provide it ;) I have a 10 x 10 grid of cells on the screen and I would like each one of them to highlight when the mouse moves over it and of course dim again as the mouse leaves the area. Each cells is an object with member variables x,y,width and height, so I created a list of 100 cell objects, each with the appropriate values in the member variables as needed to display it 10 x 10. The question I have is: Is there an algorithm or some advice some of you gurus can provide me with to effiently determine over which cell the mouse pointer currently is? The only way I can think of doing it, is to traverse through the object list every time and work out if the mouse_x, and mouse_y falls within the boundaries of a cell, but that seems to be such an inefficient way of doing it, because it has to be done every time the mouse moves. Any ideas?
MJP
MJP
If the cells are all uniformly spaced and you know where the grid starts (AKA the upper-left corner of the grid) you can calculate the highlighted tile directly without having to iterate over the cells.

gridX = mouseX - gridPosXgridY = mouseY - gridPosYIf (gridX < 0) Or (gridX >= gridSizeX) Or (gridY < 0) Or (gridY >= gridSizeY)   mouse is off the grid gridX = gridX / gridNumCellsXgridY = gridY / gridNumCellsY

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.