Enemy AI: How to make the enemy track and shoot the player

Scenario:
When the enemy does not detect any obstacles near the player or along a straight line without obstacles, it shoots a bullet toward the player. On the other hand, if the enemy detects an obstacle blocking its shot, it will move until it has a clear line of fire again.

Example for clarity:

Imagine the enemy trying to shoot the player. If nothing is in the way, it shoots directly. If something blocks the shot, it moves to reposition until it can shoot safely.

I would appreciate any advice or tips on designing the AI for this enemy effectively :slight_smile:

Umm i know how to make it shoot towards the player and go around the obstacle but are you sure you want it to not shoot when the obstacle is there? cause it will not effect anything as far as i know. :slightly_smiling_face:
If u do np just let me know.

I’m starting to find a solution; explaining mechanics is a bit tricky for me. :sweat_smile:
The idea is that the enemy should not shoot if there’s an obstacle in front of the player.
Example:
The enemy can move, but under certain conditions. The behavior works like this: the enemy detects the player directly; if there are no obstacles, it shoots. But if the player is behind an obstacle, the enemy does not shoot, it moves to find a clear line of sight, and once it detects there are no obstacles, it shoots at the player.

1 Like

Ok, umm… im not sure exactly how to do the part where it dosent shoot if obstacle is in front of it but i think u can use ray casting not sure how tho… :sweat_smile:

is this 3d? could it fire a hidden bullet and if that hits an obstacle it moves?
Ah - only just realised the pictures suggest this is 2d top down - so you can raycast at angle between enemy and player. If raycast hits obstacle then turn on pathfinding behaviour and move the player and raycast again

1 Like

Fortunately, I have already designed a bot that does the exact same.

It is very easy. I can’t give you the code because I lost it.
Even if I had it, you better Do It Yourself so you learn Gdevelop.

Here is how:

You need to use ray cast to detect if the object has a clear line of sight or not.
First, use an object as a collider. (if this object was in front of the bot, it wont shoot.)
Then make a ray cast from the enemy to the player, check for collisions with collider.

If there are collisions don’t shoot, but if there are no collisions, then shoot.
You may use the Fire Bullets behavior, to implement the shooting behavior.

You may use the pathfinding behavior to move the enemy close to the player.


I suggest you read this while making the bot:

Summary of the post above

Ray casts don’t invert their results when you invert the condition!
Use the “not” condition to inverse the result.

Here is how I implemented ray casts for my racing game:

2 Likes