I’m trying to create a game with a movement system like final fantasy tactics. I have made it so the code selects a unit and moves the cursor to the unit. Then you can move the cursor to select a place within the movement range of the unit, as long as the place is not occupied by another unit. The problem is that I don’t know how to prevent the selection of a space behind a unit.
This is what I have done so far. I don’t know how to check if a point is in the array because I can’t figure out how to make Array.contains work in the Check function.
I would store the possible fields in a collection and then use a recursive function starting from your player position to get all the walkable tiles. Would look something like this (just pseudocode):
// a simple struct to hold information about your tile
// use and extend as you see fit
public struct Tile
{
bool isBlocked; // is the tile blocked (occupied by player/enemy)
Tile[] neighbours; // the tiles that are directly reachable from this one (probably the 4 or 8 neighbouring ones)
}
//the list that will hold all your walkable tiles
List<Tile> tileList = new List<Tile>();
void CheckWalkables(Tile tile, uint stepsMoved)
{
//add the tile to the list
tileList.Add(tile);
if(stepsMoved < maxMovement) // we can walk another step
{
Tile[] neighbours = tile.neighbours; // get the neighbouring tiles
foreach(Tile currentTile in neighbours)
{
//the tile is not blocked and not yet on the list
if(!currentTile.isBlocked && !tileList.Contains(currentTile))
{
//continue searching from there
CheckWalkables(currentTile, stepsMoved+1);
}
}
}
}
Preventing the selection of space behind the unit involves counting the ‘path’ to that space. For example, in your second picture, you can’t get to the yellow spaces because the nearest one is four squares away and your green box clearly can only move three squares.
I handle it by computing how many squares of movement it would take to get there, then simply checking against my available movement. In your javascript there it’d be pretty easy to either prototype a method into “tile” or you could have a seperate method that takes a tile and the chosen unit and does the check.
If you need to get into pathing algorithms, there’s the easy way or the fun way, but thats a different question.