My raycast bullets don't work when moving

I am making a raycasting gun and the issue I am having is when the player is moving the bullet is delayed and it doesn’t come out of the barrel instead it shoots from where the position of the barrel was a second ago. How can I speed it up so it is instant.

robloxapp-20210508-0642593.wmv (1.7 MB)

remote.OnServerEvent:Connect(function(player, position)

local shootPart = tool.Parts:WaitForChild("Barrel")

local origin = shootPart.Position

local direction = (position - origin).Unit

local result = Workspace:Raycast(shootPart.Position, direction*300)

local intersection = result and result.Position or origin + direction*300

local distance = (origin - intersection).Magnitude

-- Creating Ray --

local bullet_clone = ServerStorage.Bullet:Clone()

bullet_clone.Size =, 0.1, distance)

bullet_clone.CFrame =, intersection)*, 0, -distance/2)

bullet_clone.Parent = Workspace

Unfortunately, this is caused from ping. (or the time it takes for your user to communicate to the server to replicate/draw the bullet)

To address this, you could instantly cast a ray and draw the bullet locally, so the client sees it immediately, and then you could utilize :FireAllClients() from the server to replicate the same bullet for other users to see it as well, this would just be for visuals. Do damage/hit detection server-sided.

As C_Sharper said, this is how I handle it.

When fired:
     Visualize the ray locally.
Tell the server to visualize the Ray.
     Server sends that information to all clients except the sender.
Client gets the information.
     Visualizes the ray.

In theory it should be instant for the client but not for others, it’s not a big deal but it should work.