vendredi 17 avril 2015

Merging blocks with premade images and borders for a game

After reading this question through, I realised that even I wasn't able to understand myself. So please allow me to try again.

I'm trying to make a program in Java. The program has a multidimensional array of blocks like so:



Block[][] block = new Block[worldWidth][worldHeight];


A block is basically just an ID.



public class Block {

int id;

public Block(int id) {
this.id = id;
}}


The program allows you to click somewhere on the screen and a block will be spawned there. Each block has a different image. To make it look smoother I'd like to make blocks "melt" together when they are adjecent, you see this quite often in games. To do this I made 13 images that are 1/4 block, and I tried to make a program that would automatically pick the right image to make several blocks look like one big chunk. I got everything working, but I doubt the efficiency of my code.


Here's what I did:


Divide each block into 4 sub-blocks.

Then for each sub-block I'd run the following code:



int value;
if (block[x][y].id > 0) { // id 0 represents air, or no block.
if (block[x][y].id == block[x-1][y-1].id) value++;
if (block[x][y].id == block[x][y-1].id) value += 10;
if (block[x][y].id == block[x+1][y-1].id) value += 100;
if (block[x][y].id == block[x-1][y].id) value += 1000;
if (block[x][y].id == block[x+1][y].id) value += 10000;
if (block[x][y].id == block[x-1][y+1].id) value += 100000;
if (block[x][y].id == block[x][y+1].id) value += 1000000;
if (block[x][y].id == block[x+1][y+1].id) value += 10000000;
if (value == 1011) g.drawImage(lowerRightCorner); //because the sub-blocks on the left, on top and on the upper-left are the same id as this sub-block.
etc.
}


This code works the way I want it to, but I'm pretty sure there is an easier way, because this requires me to configure all 13 possibilities (though still better than my previous 47). So my question is, is there an easier way to do this? Hope my question is clearer this way. :)


Aucun commentaire:

Enregistrer un commentaire