Raycast lagging behind

  1. What do you want to achieve? Keep it simple and clear!
    I’m trying to figure out how to fix the raycast beam lagging.

  2. What is the issue? Include screenshots / videos if possible!

Here is the code I am using for the laser part (LocalScript)

local beam = script.Parent:WaitForChild("Beam")
local p1 = script.Parent.p1
local p2 = Instance.new("Part")
p2.Size = Vector3.new(0.1,0.1,0.1)
p2.CanCollide = false
p2.CanQuery = false
p2.Anchored = false
p2.Transparency = 1
p2.Parent = game.Workspace
local l1 = Instance.new("Attachment")
local l2 = Instance.new("Attachment")	
l1.Parent = p1
l2.Parent = p2
beam.Attachment0 = l1
beam.Attachment1 = l2
local rs = game:GetService("RunService")

rs.RenderStepped:Connect(function()
	local origin = script.Parent.Position
	local direction = script.Parent.CFrame.LookVector.Unit * 1000

	local ray = workspace:Raycast(origin,direction - origin)
	if ray then
		p2.Position = ray.Position
	else
		p2.Position = direction		
	end
end)
  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I have looked, but couldn’t find anything that could help.
1 Like

Maybe use Heartbeat event instead of RenderStepped?

It has the same issue, just checked.

I guess, you’re casting ray too much on every single frame.
Try to delay the code:

local beam = script.Parent:WaitForChild("Beam")
local p1 = script.Parent.p1
local p2 = Instance.new("Part")
p2.Size = Vector3.new(0.1,0.1,0.1)
p2.CanCollide = false
p2.CanQuery = false
p2.Anchored = false
p2.Transparency = 1
p2.Parent = game.Workspace
local l1 = Instance.new("Attachment")
local l2 = Instance.new("Attachment")	
l1.Parent = p1
l2.Parent = p2
beam.Attachment0 = l1
beam.Attachment1 = l2
local rs = game:GetService("RunService")

rs.RenderStepped:Connect(function() -- Event when frame is starts to be rendered
	local origin = script.Parent.Position
	local direction = script.Parent.CFrame.LookVector.Unit * 1000

	local ray = workspace:Raycast(origin,direction - origin)
	if ray then
		p2.Position = ray.Position
	else
		p2.Position = direction		
	end
    rs.Heartbeat:Wait() -- Yielding code after frame is rendered
end)

Don’t raycast to the Position of the hit, just Raycast straight forward from the gun the distance to the hit.

2 Likes

Works like a charm! Thank you!

1 Like

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