Help with my lock on system: Am I over engineering this? Anyway to optimize this?

The question is basically asking if raycasting in a renderstepped loop for a lockon system is good.

I’m making a lock on system which uses the position of the head and the camera’s lookvector, and create a raycast on userinput.
Now, I need it to stop locking on past a distance, my solution for this is in the Renderstepped loop. I cast a ray, again from the head and using the camera’s lookvector. It works great, since the camera already angles itself towards the NPC.

Now, I have tried magnitude. It wasn’t consistent. The ray would hit at 10 studs, but because of the way that magnitude works (takes position from the center of the part, instead of hitting geometry or bounds of part), it doesn’t pass the guard clause in the renderstepped loop, which would check the magnitude.

Raycasting does this perfectly though, since it hits the actual part geometry (to some extent, I think it just hits parts bounds but close enough). I’m not sure if it’s performance intensive though. Help plz.
Will provide script when I get home.

my first thoughts on this

  • raycasting isn’t computationally expensive so don’t worry about that
  • you could probably use .Heartbeat or .Stepped instead of .RenderStepped
  • if the process is still too expensive, and you really wanted to, you could go through some standard optimizations
    • Look for places where memory can be sacrificed for performance, ex: Storing the player’s head in a variable so you don’t have to look it up every frame, or not re-creating RaycastParams every frame
    • Raycast on only some frames and not all of them (every 0.2s?)
    • Desyncronize the raycast (gets complicated)

whether or not you should optimize it though: if it isn’t broke, don’t fix it

1 Like