Wednesday, 29 September 2010

Line of sight algorithm

I have been trying to find a algorithm which when given a integer which will determine "sight range" will produce a two dimensional array containing all the x,y values of tiles which fulfill x+y<=sight range in both positive and negative directions.

This is the method I used to accomplish this:

for (int y=0;y&lt;mapHeight;y++)
{
for (int x=0;x&lt;mapWidth;x++)
{
if(currentMap.getUnit(x, y)!=null)
{
int sightRange = currentMap.getUnit(x, y).getMovementRange()/2;
for(int sightStepY = -sightRange;sightStepY&lt;sightRange;sightStepY++)
{
for(int sightStepX = -sightRange;sightStepX&lt;sightRange;sightStepX++)
{
if(x+sightStepX>=0&&x+sightStepX&lt;mapWidth&&y+sightStepY>=0&&y+sightStepY&lt;mapHeight)
{

if(sightStepY>=0&&sightStepX>=0)
{
if(sightStepY+sightStepX&lt;=sightRange)
{
currentMap.fogArray[x+sightStepX][y+sightStepY]=0;
}
}

if(y+sightRange&lt;mapHeight){
currentMap.fogArray[x][y+sightRange]=0;}
if(x+sightRange&lt;mapHeight){
currentMap.fogArray[x+sightRange][y]=0;}


if(sightStepY&lt;=0&&sightStepX>=0)
{
if(sightStepX-sightStepY&lt;=sightRange)
{
currentMap.fogArray[x+sightStepX][y+sightStepY]=0;
}
}

if(sightStepY&lt;=0&&sightStepX&lt;=0)
{
if(-sightStepX-sightStepY&lt;=sightRange)
{
currentMap.fogArray[x+sightStepX][y+sightStepY]=0;
}
}

if(sightStepY>=0&&sightStepX&lt;=0)
{
if(sightStepY-sightStepX&lt;=sightRange)
{
currentMap.fogArray[x+sightStepX][y+sightStepY]=0;
}
}

}}}
}}}
Fog array is the two dimensional array which states if the tile should fog(1) or not (0).
Here is an example of the result when rendered in the game:



I think the above is rather messy and was achieved with a good deal of trial and error. I'm sure there is a more elegant way of achieving this. Any suggestions would be appreciated.

Pathfinding needed for multiplayer stratagy?

While developing my tile based strategy game I always assumed I would need path finding. I reasoned that when the user moves a unit from one tile to another the game would need to find the most efficient path. Yet this has a major drawback. A pathfinder would remove choice from the user. There will be cases where the user may want to move along a path that does not take the optimal route. Perhaps he wants to move around an enemy scout or keep out of range of artillery?


In this case he may want to dictate the movement of the unit it a more defined way. The player may wish to draw the path. This is what I am going to use in my tile based game. The real challenge seems to be making the drawing of the path intuitive.Perhaps if the unit is being moved into fog of war in this manner the player may route the path over an enemy unit. In this case I assume the best solution would be to let the player submit the move and then have the enemy unit "block" the moves progress. Many tile based games such as civilisation have adopted this approach.