I have a grid of images, like a 2D tile set. This method is supposed to give me the image from the tile set when I just give the the tile index.
Can anyone see where my math is screwed up? Currently this function just gives me n and n.(random decimal) for the x and y.
- (CGImageRef)tileFromTileset:(int)gid {
CGImageRef tile;
CGPoint point;
CGFloat fGid = (CGFloat)gid;
point.x = fmodf(fGid, tileSource.size.width);
point.y = (fGid - (fmod(fGid, tileSource.size.width)) / (tileSource.size.width) + 1);
NSLog(@"%@", NSStringFromCGPoint(point));
tile = CGImageCreateWithImageInRect([tileSource CGImage], CGRectMake(point.x, point.y, kTileWidth, kTileHeight));
return tile;
}
I think you have a simple error of units. At the moment, you’re dividing a number representing an index by a number representing a coordinate; the unit that you end up with is therefore “index per coordinate”.* What you want, though, is just coordinate units.
The assignment to
point.xshould therefore be:That is, the tile index (units: “index”), multiplied by the width of one tile (units: “coordinates per index”), gives you its location if this were a single row of tiles (units: “coordinates”). Taking the remainder after dividing by the actual width of a row of tiles gives you the correct x coordinate.
For
point.y, you need the quotient of the same calculation:The index, multiplied by the width of a tile, divided by the width of a row, tells you how many rows are completed at that index; multiply by the height of a tile to get the coordinate.
This might be even clearer with one more constant,
kNumTilesInRow:*You keep getting
nback because, forabs(n) < abs(m),n % malways equalsn.