Grabbing Index with Coordinates?

Started by G_G, April 09, 2011, 01:09:16 pm

Previous topic - Next topic

G_G

Alright so heres this icon set.
Spoiler: ShowHide


The index to grab icons starts at 0 and in the upper left corner and goes to the right adding one to the index. Now I'm trying to make it so when the user clicks on the icon set it'll grab that icon. I'm just having troubles getting an index using the x and y locations of the mouse.

So x is 24 and y is 24. The icon that should be selected would be the 2nd icon on the second row. The index would turn out to be 17. How do I accomplish this? I know its just a simple equation but I can't seem to figure it out.

winkio

April 09, 2011, 01:12:33 pm #1 Last Edit: April 09, 2011, 01:13:43 pm by winkio

int index
x = (index % 16) * 24
y = (index / 16) * 24


EDIT: oh, you want to do it backwards too:


int x, y
index = (y / 24) * 16 + x / 24

G_G

Thanks winkio. I knew how to get the x and y from an index, just wasn't sure how to reverse it. Thanks :3

winkio

I mean, if you have the first one, it's easy to solve for the second one, it's just algebra.
Also, since x and y are ints, you don't have to round them to the nearest 24x24 index, so the position (28, 35) would still return index 17.  Pretty useful.

Blizzard

This is one of the great things about integer arithmetic.
Check out Daygames and our games:

King of Booze 2      King of Booze: Never Ever
Drinking Game for Android      Never have I ever for Android
Drinking Game for iOS      Never have I ever for iOS


Quote from: winkioI do not speak to bricks, either as individuals or in wall form.

Quote from: Barney StinsonWhen I get sad, I stop being sad and be awesome instead. True story.