How to stop a localscript from running unnecessary visual elements outside the player's view to save performance?

Hello! I’m trying to make a magic ability that when a player activates it, it will be fired to all clients and then the trajectory be played on a local script. But I had an idea to optimize performance which is to stop the visual parts of the script from running unless it’s in your players visible view, that way it doesn’t eat up unnecessary memory.

I might have an idea of how to do this, which I could try to write down later, but I’d like to be able to add this to more parts of a larger game to stop other things from running as well, but
does anyone know how to go about this? Or is it even a feasible idea?

Firstly, nice username :+1:

I wouldn’t really be concerned in doing this unless the attack itself is very expensive to update, and causes noticeable hitching just by running on the client device. So my first suggestion is to really determine if this needs to be done, because usually if the attack is handled on the client there’s no reason to do this.

But if you did want to implement something to do this, you could possibly use dot products to compare the looking direction of player’s camera to see if it’s within range of the attack’s position.

local function isAttackVisible(attackOriginPos)
local dirToAttack = (attackOriginPos - char.PrimaryPart.Position).Unit
local lookDir = camera.CFrame.LookVector

local diff = dirToAttack:Dot(lookDir) --//Compare both directions and get a scalar (-1 to 1)

--//you might need to mess around with this part. I believe anything in the negatives should be out of camera view.
return diff > 0
end

Also note this doesn’t account for camera zoom, so it may not be entirely accurate. Again, my advice would be to really see if you need to implement a system like this. You might not even have to if there’s no noticeable performance loss during the execution of those attacks.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.