How can I make realistic AI?

Hello Devs,
I am currently making a game that includes AI, I have the basics down but what I want to achieve is the following:
whenever a player is not in sight of the entity, the entity will just roam around slowly, without running into any walls or something, and when the entity spots someone, it will run at them faster.

by what i want to create i can infer that i have to use raycasting, and since i am not experienced with that either, i would appreciate any help on that as well

thank you in advance :slight_smile:

This isn’t really AI though. If you want actual AI, there’s an post on machine learning. Anyways, if you want to accomplish this, you can cast a ray from their humanoidrootpart. If the player is at least 10 studs close and the ray hits the player, then the npc will attack and move at someone.

This can be a problem with multiple players though, you’d have an npc constantly alternating from one player to another and it won’t be able to decide who to attack.

oh so i’ve been doing the whole thing wrong :sweat_smile:

guess i gotta re-write my entire system

You don’t have to use raycasting except for collision detection. If you are planning on having multiple NPC’s like this it’d be better to make a system that keeps track of all player and NPC objects. Then you would find the nearest player object to the NPC object and check if it’s in the sight of the npc object. This can be done by getting the dot product and comparing the result to distance parameters and maximum angle of vision. If it is in sight then you raycast in the direction of the player from the position of the npc to determine if there is a wall that blocks view of the player. If there isn’t, then the npc can attack the player.

Also, to solve the problem that @libriumdev mentioned

you can solve this with two things. First, you could filter through all player objects that are within sight and find the one closest to the npc. This would solve most of the issue, but it still leaves a problem when the npc is in the process of attacking one player and a different player becomes the nearest player. Normally the npc would then switch to attacking that player. You can solve this with a Target variable for each npc that decides what it’s attacking (targeting). Then, you only have to change this target to a different player for your own parameters. Several things I can think of to make the npc’s more unique:

  1. Detection for the player(s) that are attacking the npc. You could then have a threshold for the time in-between attacks. If the x amount of time passes without the player attacking then the npc ignores the player.
  2. An attack range that the npc with chase the player out until they are out of this range. Or, an amount of the npc chases the player for once they are out of the attack range.
  3. Combining multiple conditions
  4. Randomizing values
  5. Combining conditions and randomizing values
1 Like