954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Code for getting tile info

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. :)

CoolGamer48
Posting Pro in Training
401 posts since Jan 2008
Reputation Points: 77
Solved Threads: 40
 

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 =<strong> int(</strong>current frame / number of columns<strong>) </strong>* sprite height 

( where <strong>int </strong>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

MattEvans
Veteran Poster
Moderator
1,386 posts since Jul 2006
Reputation Points: 522
Solved Threads: 64
 

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...

CoolGamer48
Posting Pro in Training
401 posts since Jan 2008
Reputation Points: 77
Solved Threads: 40
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You