So in this game I'm programming the "board" is an Array of tiles. I have to get which type of tile is at certain positions and move them around. Not every position that could have a tile has a tile.
I see two ways of doing this.
1) Have a 2D Array of tiles. The dimensions of the board in tiles would be equal to the dimensions of the Array. Places where there is no tile would be represented by null. These would be organized so that myArray[1][1] would refer to the tile at (1, 1).
Pros: Easy to find a tile at a specific coordinate
Cons: Seems bulky, many of the Tiles in the array will be null.
2) Have a regular unordered ArrayList of tiles. Since tiles have an x and a y component, I do not need to sort this.
Pros: Lightweight, takes less memory
Cons: When I need to find a tile at a specific coordinate I will need to use a for loop and search through every tile
Thanks :)
The question in my mind is: is it better to use a concrete array or a sparse array, and the solution (again in my mind) is "it depends". If your universe is potentially very large, then definitely use the sparse array, else you'll be wasting resources on cells that have no current relevance. If on the other hand the universe will be well limited in size, then the convenience of a concrete array (or some type of collection) will come to the fore.
You can try hashmap. Where keep the coordinate as key. And tile value at value position.
Ex pos(2,3)->2.3 so on ..
This way search and memory both can be optimized.
Related
I have a collection of java.awt.Shape objects covering a two-dimensional plane with no overlap. These are from a data set of U.S. Counties, at a fairly low resolution. For an (x,y) latitude/longitude point, I want a quick way to identify the shape which county contains that point. What's an optimal way to index this?
Brute force would look like:
for (Shape eachShape : countyShapes) {
if (eachShape.contains(x, y)) {
return eachShape;
}
}
To optimize this, I can store the min/max bounds of the (possibly complex) shapes, and only call contains(x, y) on shapes whose rectangular bounds encompass a given x,y coordinate. What's the best way to build this index? A SortedMultiset would work for indexing on the x minima and maxima, but how to also include the y coordinates in the index?
For this specific implementation, doing a few seconds of up-front work to index the shapes is not a problem.
If possible you could try a bitmap with each shape in a different color. Then simply query the point and the color and lookup the shape.
This question is outside the scope of Stackoverflow but the answer is probably Binary Space Partitioning.
Roughly:
Divide the space in two either on the x coordinate or y coordinate using the mid-point of the range.
Create a list of counties on the two sides of that line (and divided by that line).
On each side of that line divide the collections again by the other dimension.
Continue recursively building a tree dividing alternately by x and y until you reach a satisfactory set of objects to examine by brute force.
The conventional algorithm actually divides the shapes lying across the boundary but that might not be necessary here.
A smart implementation might look for the most efficient line to divide on which is the one where the longest of the two lists is the smallest.
That involves more up front calculation but a more efficient and consistently performing partition.
You could use an existing GIS library like GeoTools and then all the hard work is already done.
Simply load your shapefile of counties and execute queries like
"the_geom" contains 'POINT(x y)
The quickstart tutorial will show you how to load the shapes, and the query tutorial will show you how to query them.
Having min an max values of coordinates of the bounds not guarantee that you can determine if one point is in or out in any situations. If you want achieve this by yourself you should implement some algorithm. There's a good one that is called "radial algorithm", I recommend that uses this, and it isn't so complicated to implement, there are sufficient bibliography and examples.
Hope this help.
I want to know what I should use for 2-dimensional positions for a Sprite.
I see Dimension objects referring to size, mainly around GUI components.
I was thinking about doing int[2], but it could easily be sabotaged by inserting in an empty array or one with the incorrect number of elements.
I only see Point objects around Mouse positions, so I don't know if it has the same purpose as what I'm looking for.
I have no idea what to choose for my purpose.
I'm currently working on making a 2d tilebased game in java.
The way my game works right now is: Finding out which tiles are inside the screen area, then rendering these. The tiles are stored in an int array, where each tile is represented by a number.
For example 1 is grasstile and 2 is dirt tile.
It uses a getTile method to decide what numbers is at the specific coordinates, then returns a tiletype based on what number is at that coordinate, example:
int[] tiles=new int[width*height];
if(tiles[x+y*width]==1) return grassTile;
else if(tiles[x+y*width==2]) return dirtTile;
else if..... and so on
But i'm wondering if it would be more efficient to make an array of tile objects?
Tile[] tiles=new Tile[mapWidth*mapHeight];
return tiles[x+y*width];
I'm wondering what is best performance wise?
Sorry if this is a bad question. I'm new to programming and I can't seem to find this anywhere else.
Thanks you!
The performance cost of either of those methods is so positively tiny compared to the cost of doing graphical rendering that you really shouldn't care. Instead of worrying about performance there, you should focus on writing clear, robust, extensible code. With that in mind, I'd recommend:
1) Use a Tile class. It will allow you to add much more than tile_types to them later on.
2) Use new Tile[mapWidth][mapHeight], and address tiles as tiles[x][y]. This approach costs more memory, and you will have to create all of the sub-arrays yourself, but it guards you against a lot of easy-to-make off-by-one errors, and other mathematical mistakes.
For the sake of argument, let's say I want to place a wall object (for simplicity, let's pretend it's just a 1x1 square) on a 2d grid which is 20x20. Let's say I have the object modeled out in coordinates between 0 and 1.
So, my question is, using openGL in the correct manner (I realize there are plenty of ways I could change the coordinates manually, but that doesn't edify me for the future), how do I place this object on the grid in the location (5,5)? Would it be related to the model matrix?
Yes, I think you have the right idea.
If your wall exists in model space from (0,0) to (1,1), and you want to position a particular instance of this wall at (5,5) through (6,6), than an appropriate thing to do would be to draw this wall with a Model Matrix that is translated by 5 units in the x and y direction.
You should not use the transformation matrices to place single primitives. Everytime you change a uniform (aka matrix) it's very likely the rasterizer pipline must be flushed, which is a sure performance killer.
As a general rule, to be efficient, a given transformation matrix should be applied to at least 100 primitives within a scene. So if you have some grid of tiles, it's better to either duplicate-translate them into a larger Vertex Array, or use instancing (if available).
I'm programming a Bomberman in Java following a tutorial (this is my first game).
The tutorial suggests the following code for detecting collisions.
for (int p=0; p<entities.size(); p++) {
for (int s=p+1; s<entities.size(); s++) {
Entity me = (Entity) entities.get(p);
Entity him = (Entity) entities.get(s);
if (me.collidesWith(him)) {
me.collidedWith(him);
him.collidedWith(me);
}
}
By now, entities is an array list containing the enemies and the player.
As I want to also detect the player collides with walls, should I put every single wall or bricks tile in the level into the entities arraylist? If so, isn't this algorithm very inefficient? These tiles aren't going to collide with other tiles, so I was thinking to manage game entities in different lists. What do you suggest? Is there a more efficient algorithm to do it?
Note: I already read other questions related to collisions in 2D games.
Thanks a lot.
I suggest reading this excellent article about how ghost movement and collision detection works in PacMan.
Then I would suggest logically modeling your Bomberman levels as a collection of tiles. Each tile represents a discrete position in your level, and it is not logically possible to ever be "between" tiles or occupying two tiles at the same time. Each tile can track what sort of terrain feature is currently on it, and whether or not it is a valid destination tile for the player (and the enemies, potentially with different rules for each if the enemies are allowed to traverse terrain that is normally impassable for the player).
Then you don't need a collision detection algorithm for every object in the world. When it comes time for an enemy to move, or when the user tries to move their character, all you have to do is check all the tiles that are adjacent to their current tile (4, or 8 max if you allow diagonal movement), see if each tile represents a valid movement direction, and block the movement if it is not in a valid direction.
And to answer your question, yes, iterating every object in the world on every position update will be very inefficient.
There is another way to use grids for collision system. I'm using more complex version of the Aroth's suggestion and using this to fix collision bugs.
Theoretically this system is the fastest(assuming you are doing this check if(Grid[x][y] ==true)) because it only uses a single Boolean check for each entity(the things that can move).
Note: In the above grid check example, I've used a 2 dimensional array of booleans that sets the coordinates of impassable grids to false.`
If you are not worried about physics like bouncing from a wall you can use this:
1- Divide the map into grids.
2- Making every entity only fill a tile would be better but not necessary.
3- Store the previous position or the grid of the entities.
4- Whenever an entity moves, before visually updating their location (also before
doing other calculations) check the grids they are in. If they are in grid
that is not empty or simply in a grid that they are not supposed to
be, return their position back to the previous position (which you have stored).
If you want to allow entities to move freely inside the grids(the grids are bigger than the minimum distance they can move) then you need to put them adjacent to the grids they've entered and they weren't supposed to. Otherwise just return them back to the previous grid.
If you want them to bounce from the wall you can still use this but I'm not sure how many features can be added to a collision system like this.
May I recommend my own project. But it's still wip.
https://github.com/YagaoDirac/Dirac-2d-collision-detection-for-games
It's based on quad-tree which handles sparse pretty well.
It supplies collision group. This conception is also used in both UE and Unity.
It support only circle vs circle and overlapping only for now(2022 feb 22).
I plan to make at least AABB, and collision which at least stop your pawn from leaving the map.
I may also provide another system based on fixed grid.