Showing actor movement range on tiles - java

I am trying to write something that will take a X and Y coordinate and a value that represents the available movement points the selected actor has. It should then output a list of the reachable locations so that I can highlight those tiles when the actor is choosing where to move.
I managed to use a function from my pathfinding library (https://github.com/xaguzman/pathfinding) that gives me the neighbouring tiles of a tile as a List of grid cells. It can also check my Tile-map and see if the tile is walkable.
What I can't really get my head around is how I would be able to set this up so that it would run as many times as the movement points.
List<GridCell> neighbours;
NavigationTiledMapLayer navLayer;
public void getMovementPossibilities(int tileX, int tileY) {
GridCell cell1;
GridCell cell2;
cell1 = navLayer.getCell(tileX, tileY);
GridFinderOptions opt = new GridFinderOptions();
opt.allowDiagonal = true;
opt.dontCrossCorners = false;
neighbours = navLayer.getNeighbors(cell1, opt);
for (int i = 0; i < neighbours.size(); i++) {
int nX = neighbours.get(i).getX();
int nY = neighbours.get(i).getY();
cell2 = navLayer.getCell(nX, nY);
neighbours.addAll(navLayer.getNeighbors(cell2, opt));
}
}

Sounds like a case for recursion. I can't see how you're keeping track of movement points but your current method finds all tiles 1 distance away. Inside this method, you need to recall the same method, but with each of those neighbours as your new start point and with the movement points reduced by 1.
This in turn generates all the second neighbours, and then the method will be called recursively and so on...
You will want a check at the top of the method so that if the distance points left are 0, it just immediately adds the current tile to neighbours and then returns (to stop the recursive chain going on forever).

Related

How to implement multiple walls that detect intersection in Java GUI

I have a GUI Maze game that I am creating and I am having trouble implementing walls that prevent the player from moving. The walls are rectangles but the player is a circle so I had to create a collision detection method between a rectangle and a circle. The problem I am having is that my collidesWith() method is in the player class and it takes a single wall as a parameter and returns a string that tells you which side of the wall is the player intersecting with. This means I can only check if the player is colliding with one wall at a time. Here is the code for the collidesWith() method. x and y are the x and y coordinates of the player since this method is in the player class:
I should mention that the code above doesn't exactly work how I wanted it to since it only works when the player is coming from the sides. If the player is coming from the top or bottom, the player just goes through the wall.
The reason I need this method to return a string to tell me where the player is coming from is so that I can explicitly restrict the movement of the player when the up, down, left, right keys are pressed. This is in another class where all the GUI components are. Here is the code for that. I have created a wall object on top so that it can be passed as a parameter here when checking for intersection:
In my view, it is better to avoid to iterate through the whole array of wallsArraylist. If I understood correctly, it is necessary to explore neighbour cells, if yes, then you can explore neighbours in a two-dimensional array using this approach:
(pseudo-code)
row_limit = count(array);
if(row_limit > 0){
column_limit = count(array[0]);
for(x = max(0, i-1); x <= min(i+1, row_limit); x++){
for(y = max(0, j-1); y <= min(j+1, column_limit); y++){
if(x != i || y != j){
print array[x][y];
}
}
}
}
In addition, try to avoid magic strings. Replace "comingFromRight" and etc to constant string:
public static final String COMING_FROM_RIGHT = "comingFromRight";

My game collision system doesn't work on more than one tile

I'm working on a collision system for my game, however I can't get it to work, if I add more than one wall (which is the object I'm rendering) the collision system doesn't work and I can get through the block.
However if I leave only one wall the collision works correctly, or if at the end of the loop I add a break;
the collision works but only on the first wall of the map, the others don't get the collision.
Would anyone know how to solve this? I've been trying to solve it for 2 days and I couldn't.
public boolean checkCollisionWall(int xnext, int ynext){
int[] xpoints1 = {xnext+3,xnext+3,xnext+4,xnext+3,xnext+3,xnext+4,xnext+10,xnext+11,xnext+11,xnext+10,xnext+11,xnext+11};
int[] ypoints1 = {ynext+0,ynext+8,ynext+9,ynext+11,ynext+12,ynext+15,ynext+15,ynext+12,ynext+11,ynext+9,ynext+8,ynext+0};
int npoints1 = 12;
Polygon player = new Polygon(xpoints1,ypoints1,npoints1);
Area area = new Area(player);
for(int i = 0; i < Game.walls.size(); i++){
Wall atual = Game.walls.get(i);
int[] xpoints2 = {atual.getX(),atual.getX(),atual.getX()+16,atual.getX()+16};
int[] ypoints2 = {atual.getY(),atual.getY()+16,atual.getY()+16,atual.getY()};
int npoints2 = 4;
Polygon Wall = new Polygon(xpoints2,ypoints2,npoints2);
area.intersect(new Area(Wall));
if(area.isEmpty()){
return true;
}
}
return false;
}
I'm pretty sure the problem is this call:
area.intersect(new Area(Wall));
Here's the JavaDoc for that method:
public void intersect(Area rhs)
Sets the shape of this Area to the intersection of its current shape
and the shape of the specified Area. The resulting shape of this Area
will include only areas that were contained in both this Area and also
in the specified Area.
So area, which represents the shape of your player, is going to be modified by each test with a wall, which is why it's only working with one wall.
You could fix the issue by simply making the player Area the argument of the call, as in:
Area wallArea = new Area(Wall);
wallArea.intersect(area);
if(wallArea.isEmpty()){
return true;
}
By the way, this logic is reversed isn't it. Don't you want to check that the resulting area is not empty, i.e. there was an overlap between the player and the wall?
The other option, if each Wall is actually a rectangle, would be to use the this Area method instead:
public boolean intersects(double x,
double y,
double w,
double h)
Tests if the interior of the Shape intersects the interior of a
specified rectangular area. The rectangular area is considered to
intersect the Shape if any point is contained in both the interior of
the Shape and the specified rectangular area.
Something like this:
if(area.intersects(atual.getX(), atual.getY(), 16, 16)) {
return true;
}
As this avoids the creation of an Area object for each wall, and the intersection test is going to be much simpler, and faster.

libGDX TiledMap: Check if object exists at a specific cell

I have a TiledMap map with some object layers like "wall", "door", "spike"...
Each layer has only rectangles, at their specific positions.
What is the best way I could check if a specific cell of the tile layer contains an object from a specific object layer?
To do something like if Cell of the tile layer at (x,y) contains an object from a object layer "wall", say "can't move there".
I just started using libGDX and Tiles, and the current way of detecting something like this that I can think of would be to create all those rectangles and check if they overlap with the player rectangle each time a player moves to the next cell.
But that would be checking every single object, and I need to just check the one cell the player is currently in.
One way you could reduce computation (this only works if the walls/doors/etc. are all static and don't move or change shape) is by keeping a 2D array of booleans (basically your TiledMap) with true meaning that tile is blocked and vice versa.
In pseudocode:
// Initially all grid cells are un-blocked
boolean[][] gridBlockedByWall = new boolean[MAP_HEIGHT][MAP_WIDTH]; //Replace with your grid size
// Loop over each wall and set array (change depending on your implementation)
for (Rectangle wall: walls) {
// Here we run over every wall and column covered by this rectangle and set it as blocked
for (int row = wall.y; row < wall.y + wall.height; row++) {
for (int col = wall.x; col < wall.x + wall.width; col++) {
gridBlockedByWall[row][col] = true;
}
}
}
Now to test if position (x, y) is blocked by a wall simply do gridBlockedByWall[y][x] which will run in constant time.

libGDX - Strange Collision Behaviour

I'm having some difficulty implementing very basic collision within libGDX. The update code for the "player" is as so:
private void updatePosition(float _dt)
{
Vector2 _oldPos = _pos;
_pos.add(_mov.scl(_dt*50));
_bounds.setPosition(_pos.x-8, _pos.y-12);
if(_game.getMap().checkCollision(_bounds))
{
System.out.println("Collision Detected");
_pos = _oldPos;
_bounds.setPosition(_pos.x-8, _pos.y-12);
}
}
So, initially _oldPos is stored as the values of _pos position vector before applying any movement.
Movement is then performed by adding the movement vector _mov (multiplied by the delta-time * 50) to the position vector, the player's bounding rectange _bounds is then updated to this new position.
After this, the player's new bounding Rectangle is checked for intersections against every tile in the game's "map", if an intersection is detected, the player cannot move in that direction, so their position is set to the previous position _oldPos and the bounding rectangle's position is also set to the previous position.
Unfortunately, this doesn't work, the player is able to travel straight through tiles, as seen in this image:
So what is happening here? Am I correct in thinking this code should resolve the detected collision?
What is strange, is that replacing
_pos = _oldPos;
with (making the same move just made in reverse)
_pos.sub(_mov.scl(_dt*50));
Yields very different results, where the player still can travel through solid blocks, but encounters resistance.
This is very confusing, as the following statement should be true:
_oldPos == _pos.sub(_mov.scl(_dt*50));
A better solution for collision detection would be to have a Vector2 velocity, and every frame add velocity to position. You can have a method that tests if Up arrow key is pressed, add 1 (or whatever speed you would like) to velocity. And if down is pressed, subtract 1 (or whatever speed). Then you can have 4 collision rectangles on player, 1 on top of player, bottom, left, and right. You can say
if(top collides with bounds){
if(velocity.y > 0){
set velocity.y = 0.
}
}
And do the same for down, left and right (eg... for bottom, make sure to test if(velocity.y < 0) instead of if(velocity.y > 0).
EDIT: You code is not working because you set oldPos = pos without instantiating a new Vector2. Which means when you add onto pos, it also changes oldPos. So say oldPos = new Vector2(pos);
try to test future position before move. If collision, don't move.

Creating randomly generated objects in a 2D array

all. I'm working on a small game in which a 2D array is created to house each tile of the "map" of the game. The game spawns a player and a bunch of assorted items. The cells look like this:
private String [][] cells;
...
public void set(int cellX, int cellY, String str)
{
cells[cellX][cellY] = str;
}
with each String stating what the cell in each place looks like. For instance, sometimes a wall spawns and sometimes passages are created (this is all read in from a file). So the question is this:
How can I randomly generate objects on certain cells? For instance, if I have 36 cells total (6x6), but only 23 of them can be "moved" on by the player, how can I randomly generate items that have an equal chance to spawn on each?
The code I have thus far is this.
public void draw()
{
for (int x = 0; x < cells.length; x++)
{
for (int y = 0; y < cells[w].length; y++)
{
if(cells[x][y] == "W"){
Cell wall = new Cell(config.wallImage());
wall.draw(config, x, y);
if(cells[x][y] == "P"){
Cell passage = new CellPassage(config.passageImage());
// This is where I need to check to see if the item is okay
// to be placed. If it is unable, nothing will be added to
// the Cell passage.
//passage.attemptToAdd(item);
passage.draw(config, x, y);
}
}
}
hero.draw();
}
So, had a discussion in chat with OP and this is the problem, which seemed a little confusing from the question post:
There are Item, such as Key and Gem, that may spawn in each round.
Those Item have a limit number that must be spawned every round. For example, there may spawn 5 Gem every round.
They must spawn in passages with an equal probability.
So, to solve this issue, my suggestion is:
Creating an ArrayList of Cell. Store all the cells of passages.
Generate a random number between 0 and array length - 1.
Repeat until the limit of needed items is reached.
It should look something like this:
public void addItem(Item item, int limit)
{
ArrayList<Cell> passages = new ArrayList<Cell>();
for(int x = 0; x < cells.length; x++)
{
for (int y = 0; y < cells[w].length; y++)
{
if (cells[x][y] == "P") //if it's a passage
passages.add(new Cell(x,y));
}
}
Random rand = new Random();
while(spawnedItems < limit){
if(passages.size() == 0)
throw LimitImpossibleError();
int randomNum = rand.nextInt(passages.size());
items.add(new ItemPosition(item, passages.get(randomNum))); //assuming that you have a global ArrayList of Item and respective Cell (ItemPosition) to draw them later
}
}
Another question of the OP in the discussion was how to draw the Item later. So, I gave him 2 suggestions:
Change the representation of the maze to some Object that represents what's in the maze. For example, CellInfo, which could be parent of Wall, Passage, Item, etc. This, however, would require much change on the actual work. He's actually reading the maze from a file, for example.
Having an ArrayList with Item and the respective Cell where it should be drawn. In the draw method, after drawing all the walls and passages (the only things represented in the maze with String), traverse this ArrayList and draw them in the respective position.
You could create an ArrayList of Points that are eligible to have an item on them, and then randomly select them using [your ArrayList's name].get(Math.random() * [your ArrayList's name].size())

Categories

Resources