Question

I am trying to figure out how to make my game draw a certain tile in a specific spot using an image to represent each spot. So if a pixel of that image was the color red a specified picture(tile) would be draw in the game, and each pixel that was green stood for a different specified image. I have seen people who make games do this but I dont know how to do it and I dont know the name for it.

If you need more info I can try to explain what I want to do more. Could someone please help?

Was it helpful?

Solution

That may actually be slower in the long run. I would definitely recommend you use a byte array to represent the tiles, i.e. byte[width][height]. It will be faster, easier to manage and easier to extend to something like spriteData[width][height] if a single byte does not supply enough information anymore.

However, if you insist on using an image to store game data, you can use something like the following:

File file = new File("mygamedata.jpg");
BufferedImage image = ImageIO.read(file);

// Getting pixel color at position x, y (width, height)
int colour =  image.getRGB(x ,y); 
int red    = (colour & 0x00ff0000) >> 16;
int green  = (colour & 0x0000ff00) >> 8;
int blue   =  colour & 0x000000ff;
System.out.println("Red colour component = " + red);
System.out.println("Green colour component = " + green);
System.out.println("Blue colour component = " + blue); 

Each component will be in the range (0...255) and you can use that to determine the correct tile, i.e.

Graphics2D gfx = (Graphics2D) offScreenImage.getImage();
if (red == 120 && green == 0 && blue == 0) {
  gc.drawImage(tile[whichTileYouWantForRed], x, y, null); // where x and y is the pixel you read.
}

Alternatively, you can skip extracting the components altogether, and simply use colour, i.e.

if (colour == 0x00ff0000) {
  gc.drawImage(tile[whichTileYouWantForRed], x, y, null); // where x and y is the pixel you read.
} 

(Which will be slightly faster anyway and actually what you want.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top