Having trouble loading tiles from a spritesheet (Java android)

Started by
0 comments, last by frob 10 years, 10 months ago

Hi everyone.

I am trying to port a simple tile based 2d game from C++ into Java. This is my first go at Java and I'm having problems as this is a brand new IDE/Language/API for me and I think that I'm getting bogged down in details and it's probably my mathematics at fault, but maybe things aren't operating in the same way. Here's what I'm trying to do. The tile sprite sheets have an ID for each tile starting at 1, I need a function that can turn the ID into a x,y location. Each tile is 64 by 64 and the tile sheets are 512 by 512.

I am trying to divide the ID by 8, using the values before the decimal point as the Y location and the decimal numbers as the X location.

This seems to work fine for the first row but it breaks on all other rows.

Here is the code:


	public static void draw(int gridX, int gridY, int ID, tileLayer layer){
		int x = gridX * 64;
		int y = gridY * 64;
		
		ID--;

		float sheetPosX = 0;
		float sheetPosY = 0;
		
		float result = (float)(ID / 8f);
		
		sheetPosY = (int)Math.floor(result);
		sheetPosX = result - sheetPosY;
		sheetPosX = (int) (sheetPosX / 0.125f);
		
		System.out.println(sheetPosX + " " + sheetPosY);
		
		Rectangle rect = new Rectangle();
		rect.y = sheetPosY * 64f;
		rect.x = sheetPosX * 64f;
		rect.width = 64f;
		rect.height = 64f;
		
		if (layer == tileLayer.BACKGROUND)
			batch.draw(tileSheet, x - OffsetCamera.offsetX, y - OffsetCamera.offsetY, (int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height);
		else if (layer == tileLayer.DOODAD)
			batch.draw(doodadSheet, x - OffsetCamera.offsetX, y - OffsetCamera.offsetY, (int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height);
	}

Many thanks.

Casey

Advertisement

The tile sprite sheets have an ID for each tile starting at 1, I need a function that can turn the ID into a x,y location. Each tile is 64 by 64 and the tile sheets are 512 by 512.

Why?

Why are you starting at 1? Offsets and index values should start at 0.

Why is each tile 64x64? Is your game design such that everything is that size? Nothing is long and narrow, nothing is short and wide? Everything is square, and nothing is larger than 64x64? Why 512x512 for sprite sheets? Is there any reason you need to take control away from the artists to decide the best sprite sheet size? Artists should have a piece of metadata associated with each sprite sheet. It should include the dimensions of the object, the stride, and other features.

To convert a sprite index into a row and column, assuming all are integers:

column = index % spritesPerColumn;

row = index / spritesPerColumn;

To convert a row and column into locations:

x = column * stridePerColumn;

y = row * stridePerRow;

This assumes your artists only have one type of object per sprite sheet.

This topic is closed to new replies.

Advertisement