I was making a game with XNA game studio and now I want to rewrite it in Java. It's something like a 2D Minecraft clone. For collision detection, I have to loop through all blocks in the game to check on whether the player is colliding with a block. With a huge number of blocks, it is impossible to do so, so I made a grid system. I divided the world into grids which contain blocks, and put them into a dictionary.
Dictionary<string, List<Block>> gameBlocks;
Now I have only to loop through the blocks in the current grid.
This is the method to register a block:
public void RegisterBlock(Block block)
{
idX = (int)(block.blockPosition.X / width);
idY = (int)(block.blockPosition.Y / height);
string id = idX.ToString() + "_" + idY.ToString();
if (gameBlocks.ContainsKey(id))
{
gameBlocks[id].Add(block);
}
else
{
gameBlocks.Add(id, new List<Block>());
gameBlocks[id].Add(block);
}
}
Now I am trying to rewrite it in Java but I don't know how to put something into a Dictionary.
Use Java's Map
interface and HashMap
class. Your method would look like this in Java:
private Map<String, List<Block>> gameBlocks = new HashMap<String, List<Block>>(); // Java 6
// OR:
private Map<String, List<Block>> gameBlocks = new HashMap<>(); // Java 7
public void registerBlock(Block block) {
idX = (int)(block.blockPosition.X / width);
idY = (int)(block.blockPosition.Y / height);
String id = idX + "_" + idY;
if (gameBlocks.containsKey(id)) {
gameBlocks.get(id).add(block);
} else {
gameBlocks.put(id, new ArrayList<Block>());
gameBlocks.get(id).add(block);
}
}
Notice some of the corrections I've made for Java's recommended formatting/naming styles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With