Hey, sorry if I'm in the wrong forum, but I need some help with getting the left and top values for a tile from a tile set. A book I have gives these two formulae:

left = (current frame % number of columns) * sprite width
top = (current frame / number of columns) * sprite height

Now, I'm no expert, but these seem completely wrong.

For the left value, I came up with:

left = ((current frame-1) % number of columns) * width

This seems to work based on my testing

For top, I came up with:

top=((current frame/cols) - 1) * height

but after testing found that it only works for tiles on the right side of the set.

Does anyone know a formula I can use for the top value/check if the one I have for left value make sense/check if the original two in my book were fine and I'm just crazy. Thanks. :)

Recommended Answers

All 2 Replies

The first two look good; assuming you have a fixed number of columns and that the tileset can then extend "infinately" vertically, and the tiles are given frame indices like:

0 1 2 3 4
5 6 7 8 9
...

If you index your tiles starting from 1... don't : start using 0 as first index, the math will be alot cleaner.. But, if you must use 1-based indexing; subtract 1 from the current frame before working with it in calculations..

One thing I would do; though:

left = (current frame % number of columns) * sprite width
top =[B] int([/B]current frame / number of columns[B]) [/B]* sprite height 

( where [B]int [/B]is whatever the function is in your language to truncate a decimal to an integer - i.e. round by removing the fractional part )

If you're having problems understanding why it works: http://en.wikipedia.org/wiki/Modular_arithmetic

Hmm.... ya, you're right. The example started with tile 1, though not 0, so that was a problem, and there was no mention of using floor() (the book uses C).

Guess that might be part of the reason that version of the book is discontinued...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.