1

I'm creating a small 2D game (With Javascript) on a grid. In this game, I have 3 kind of unit types let's say:

  • green: unit which have a shot range of 1 tile (they can attack a target 1 tile around)
  • orange: unit which have a shot range of 2 tiles
  • blue: unit which have a shot range of 3 tiles

Here's a schema: grid game schema

The black square is the target. The gray one is the unit.

The movement of the unit is OK, I can move on wathever square when I want. The target is fixed.

My question is: How can I find, according the unit color (range 1,2 or 3), all the tiles where the unit will be able to shot?

I mean:

  • Blue unit can shot from: blue, orange and green tiles
  • Orange unit can shot from: orange and green tiles
  • Green unit can shot from: green tiles

I though about an ugly solution with two nested loops but, maybe there is a known algorithm to do this...

I have a (x,y) position for the target and the unit

I saw this one Algorithm for finding spaces to attack target within move-attack area on a 2D grid game board but my probleme seems to me more simple:

Can you help me?

Community
  • 1
  • 1
CyrilleGuimezanes
  • 1,598
  • 1
  • 18
  • 33

2 Answers2

1

What about this?

boolean canShot(Unit unit, Target target){
    if ((unit.minimumShotDistance <= Math.abs(unit.position.x - target.position.x) && 
         unit.minimumShotDistance <= Math.abs(unit.position.y - target.position.y)){
        return true;
    }
    return false;
}
libik
  • 22,239
  • 9
  • 44
  • 87
0

Depending on color of unit tile, set value of range=1(green), 2(orange) or 3(blue).

Now, all tiles in range (x,y) such that:

x = targetX - range to targetX + range
y = targetY - range to targetY + range
and (x,y) is within board limits

will give all the tiles from where your unit can shoot.

If you want to know that whether from its current position, unit can shoot the target or not, check if unit's coordinates (x,y) satisfy above conditions.

vish4071
  • 5,135
  • 4
  • 35
  • 65