Will this be too resource intensive?

Hi! I’m currently making an RPG and had a question. I’m making enemies, but I feel like its going to lag the game. What’s going on in the “brain” is it loops through all players and finds the nearest one then it casts a ray and checks if they are in its line of sight and it has several more for loops for various reasons. Will this lag my game?

EDIT : there will be a large quantity of the enemies

Theoretically, you don’t need to run checks to determine the closest player that frequently. For example, if a target is already given to the NPC, maybe you’d only want to check that again when the target dies or something.

Aside from that, you could make it so those checks run minimally. Perhaps twice a second or so; versus running it every Heartbeat.

Raycasting typically is pretty inexpensive, so I wouldn’t be too concerned about that part of it.

At the end of the day what I think it comes down to is how frequently the checks that determine the closest player are running. Getting the magnitude (length) property of a vector is fairly expensive, so if that runs frequently enough it might cause some load.

1 Like

what would be the best way to tell if a player is in the range of an attack? It should attack right as it’s in range but for that I think it would require a lot of magnitude calculations, which, as you said cause lag.

I can think of a few options.

Using magnitude in this scenario wouldn’t be terrible. You could do this locally to see if the user can attack, and then on the server you could verify the player’s in range of the attack by using a single magnitude check. (preventing exploits)

However if you’re really concerned about performance, another possible solution might be using raycasting with a whitelist set to only the character you’re attacking, casting the ray from the attacking player’s position with a length of the attack distance/range.

Hope this helps

Sorry for being unclear, but I want the enemy to attack the player and I don’t believe you can run local scripts for NPCs. Do you think just looping a magnitude check should be fine?

1 Like

That should be fine.

I would say just wait maybe half a second or so in between updates, so you’re not getting the vector’s magnitude too frequently; there also really isn’t a real need for that anyways.