How do I cast a ray from every friendly unit to every enemy unit?

What I’m trying to do is cast a ray from every guard unit to every enemy unit. If at least one guard can cast a ray directly to an enemy, the enemy should be highlighted.

My events look like:
Repeat for each instance of Guard
]> Repeat for each instance of Enemy
]>>Cast a ray from Guard.X(“Center”);Guard.Y(“Center”) to Enemy.X();Enemy.Y() Against Enemy, and save the results in [blank]
]>>> (sub event) Change the opacity of Enemy: 255

]>>Cast a ray from Guard.X(“Center”);Guard.Y(“Center”) to Enemy.X();Enemy.Y() Against Wall, and save the results in [blank]
]>>> (sub event) Change the opacity of Enemy: 100

The problem is that I can’t figure out a way to cast a ray from every guard. GDevelop is only taking into account the first guard I placed.

The guard on the bottom (green) should be spotting the enemy, but it is not.

I have tried to find a solution to this online but haven’t found anything comprehensible at all.

The problem will most likely be that the bottom guard is processed first, and the top one after that. So while the bottom one sees the enemy, the top one cannot and that opacity setting over-rides the bottom guards action.


My solution to that would be:

  • Add a boolean object variable to each enemy, say called isSpotted.
  • Just before you iterate over all the guards, set the variable to false and set opacity to 100.
  • Invert the second raycast, and also make it from enemy to guard.
  • Set the variable to true as a subevent of the inverted second raycast.
  • Get rid of the first raycast.
  • Set opacity to 255 for all enemy with isSpotted = true.

Also, keep in mind repeats and raycasts use a bit of processing, and ideally you should minimise their usage.