I am working on a placement module for a game. When placing objects, the module uses Raycast to find the mouse location. My issue is when to start raycasting and when to stop.
Should I constantly raycast and move objects to the calculated location when I need to, or should I only raycast when I am moving the object, or is there some other solution that I should do instead?
Roblox’s raycast is very optimized. You shouldn’t have trouble raycasting multiple times per frame. I would recommend you raycast per frame because of the example I mentioned below.
That said, it’s also important to not raycast when you don’t need to in case other processes need the CPU. So obviously start when the player is in the “building” phase and stop when they’re no longer in it.
Constantly Raycast Pros: 100% accurate with no edge cases Cons: more resource intensive
Raycast on Move/Change: Pros: Lightweight for the user Cons: Possible edge case where other factors may cause the object placement to change. For example. You hold your mouse still and a person across your mouse. This would cause the placement to change, but since your mouse hasn’t moved, it doesn’t update. How do you detect if someone walked under your mouse? Raycasts. And you’re back to square one.
I am thinking that this means the module would only raycast if the mouse is moved?
I am using RunService for raycasting. I just wasn’t sure if I should constantly run the raycast or only have it run when the player is in the “build” phase.
Thank you!
EDIT: I guess this leads me to my next question. How is the best way to completely stop a RunService.RenderStepped() function?
I know you can use BindToRenderStep(), however, I find that it doesn’t completely stop the function with you disconnect it, leading to functions getting stacked.
Save the RenderStepped in a value. This will allow you to do value:Disconnect(). Example:
local run = game:Get service("RunService")
local RenderSteppedConnection = run.RenderStepped:Connect(function(dt)
print(dt)
end)
Task.wait(3)
RenderSteppedConnection:Disconnect()
I wrote this all on my phone. So, some of it may be off.
I would recommend to not run unless you’re in the “build” phase unless it’s critical for your game to have it running indefinitely.
You can simply disconnect it to stop it from running again.
local connection = RunService.RenderStepped:Connect() -- store the connection object
-- we no longer need this renderstepped running
connection:Disconnect()
I would recommend to use .HeartBeat over .RenderStepped or :BindToRenderStep for this scenario.
From roblox’s documentations:
“RenderStepped does not run in parallel to Roblox’s rendering tasks and code connected to RenderStepped must be executed prior to the frame being rendered. This can lead to significant performance issues if RenderStepped is used inappropriately. To avoid this, only use RenderStepped for code that works with the camera or character. Otherwise, RunService.Heartbeat should be used.”