Lets see how to do it now:
0. Create a simple small line sprite outside the layout and name it 'lineofsight'
1. Click on your enemy unit and add an instance variable named 'range'. Type is number, default value is 0.
2. At start of layout,
- set the range of enemy tower/unit to WindowWidth which changes automatically if you're using a browser or mobile device according to your screen size.
- destroy the 'lineofsight' sprite .. we need to spawn it at enemy unit or it will play bad if player is at the edge of screen where it exists.
- Spawn the 'lineofsight' on layer1 (my objects layer where all player, walls, trees, enemies exists)
As shown below
3. Then every 3.0 secs (flexible to you),
- pick the nearest enemyunit to the player
- pick the nearest 'lineofsight' to the enemy (which will be what we spawned on in step2)
- set 'lineofsight' and enemy angle to align to players position
- set width of 'lineofsight' to distane between the player and enemy
3.A Check if distance is less than your decided shooting 'range' for enemy; if yes then proceed to see if its Line of Sight. How?
Since now the 'lineofsight' extends width all the way from enemy to player, you check if its passing over any solid objects that you dont want the bullets to be wasted on, or the player to be seen over from. That is
- check if 'lineofsight' is overlapping trees AND
- check if 'lineofsight' is overlapping walls AND
- so on
Be very careful here, dont put an OR relation or dont write events without AND. Because the Line of Sight needs to fail even if there is a single obstacle.
As shown below