Extremely inaccurate "laser beam" when player misses pistol raycast


I attempted to make a laser beam whenever the player misses their target or when they literally shoot at nothing (nil) but the beam is EXTREMELY inaccurate. Can anyone help please?

-- Local Script for when Pistol is activated
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UserInputService = game:GetService("UserInputService")
local SoundService = game:GetService("SoundService")

local Pistol = script.Parent
local Handle = script.Parent:WaitForChild("Handle")
local BulletRayCastPart = Pistol:WaitForChild("BulletRayPart")
local PistolFiredEvent = script:WaitForChild("PistolFired")

local LocalPlayer = game.Players.LocalPlayer
local PlayerCamera = workspace.CurrentCamera
local Mouse = LocalPlayer:GetMouse()
local PlayerGui = LocalPlayer:WaitForChild("PlayerGui")

local Flash = Handle:WaitForChild("Flash")

local Sounds = {
	EquipSound = Handle:WaitForChild("EquipSound2"),
	UnequipSound = Handle:WaitForChild("UnequipSound"),
	ReloadSound = Handle:WaitForChild("Reload"),
	TickSound = Handle:WaitForChild("Tick"),
	FireSound = Handle:WaitForChild("FireSound")
}

local GunGui = Pistol:WaitForChild("AmmunitionGui"):Clone()
GunGui.Parent = PlayerGui

local BackgroundFrame = GunGui:WaitForChild("BackgroundFrame")
local Bullets = GunGui:WaitForChild("Bullets")
local BulletText = BackgroundFrame:WaitForChild("BulletsText")

local Shootingdebounce = false
local ReloadDebounce = false
local Equipped = false
local MAX_RANGE = 200

local function UpdateBullets()
	BulletText.Text = Bullets.Value.. "/10"
end

local function Fired()
	Sounds["FireSound"]:Play()
	Bullets.Value -= 1
	Flash.Enabled = true
	task.wait(0.1)
	Flash.Enabled = false
end

local function onEquipped()
	Equipped = true
	Sounds["EquipSound"]:Play()
	GunGui.Enabled = true
end

local function onUnequipped()
	Equipped = false
	Sounds["UnequipSound"]:Play()
	GunGui.Enabled = false
end

local function onReload(input, processed)
	if processed then return end
	if input.KeyCode == Enum.KeyCode.R and Equipped == true then
		if Bullets.Value < 10 and ReloadDebounce == false then
			ReloadDebounce = true
			Sounds["ReloadSound"]:Play()
			task.wait(2)
			Bullets.Value = 10
			ReloadDebounce = false
		else
			return
		end
	else
		return
	end
end

local function onActivated()
	if Shootingdebounce == true or ReloadDebounce == true then return end
	if Bullets.Value > 0 then
		Shootingdebounce = true
		task.spawn(Fired)
		
		local Origin = BulletRayCastPart.Position
		local Direction = ((Mouse.Hit.Position - Origin).Unit) * MAX_RANGE
		local ExcludeList = {LocalPlayer.Character, script.Parent}
		PistolFiredEvent:FireServer(Origin, Direction, {script.Parent, LocalPlayer.Character}, (Mouse.Hit.Position - Origin))
		
		task.wait(0.2)
		Shootingdebounce = false
	end
end

Pistol.Equipped:Connect(onEquipped)
Pistol.Unequipped:Connect(onUnequipped)
Pistol.Activated:Connect(onActivated)
UserInputService.InputBegan:Connect(onReload)
Bullets.Changed:Connect(UpdateBullets)
-- Server Script for Raycasting and creating the laser
local Debris = game:GetService("Debris")
local SoundService = game:GetService("SoundService")

local PistolFiredEvent = script.Parent
local HeadshotSound = PistolFiredEvent:WaitForChild("Headshot")

local Pistol = PistolFiredEvent.Parent.Parent
local BulletRayCastPart = Pistol:WaitForChild("BulletRayPart")
local MAX_RANGE = 200

local function Laser_Hit(targetInstance, EndPosition, Distance)
	local Laser = Instance.new("Part")
	Laser.Size = Vector3.new(0.1, 0.1, Distance)
	Laser.Material = Enum.Material.Neon
	Laser.Transparency = 0.5
	Laser.Anchored = true
	Laser.CanCollide = false
	Laser.CanTouch = false
	
	task.spawn(function()
		if targetInstance.Parent:FindFirstChild("ForceField") or not targetInstance.Parent:FindFirstChild("Humanoid") then Laser.Color = Color3.fromRGB(255, 0, 0) return end
		
		if targetInstance.Name == "Head" then
			Laser.Color = Color3.fromRGB(255, 255, 0)
			local HeadShotSoundClone = HeadshotSound:Clone()
			HeadShotSoundClone.Parent = targetInstance
			HeadShotSoundClone:Play()
			Debris:AddItem(HeadShotSoundClone, 2)
		else
			Laser.Color = Color3.fromRGB(0, 255, 0)
		end
	end)
	
	Laser.CFrame = CFrame.lookAt(BulletRayCastPart.Position, EndPosition) * CFrame.new(Vector3.new(0, 0, -Distance/2))
	Laser.Parent = game.Workspace
	Debris:AddItem(Laser, 0.1)
end

local function Laser_Missed(EndPosition)
	local Laser = Instance.new("Part")
	Laser.Size = Vector3.new(0.1, 0.1, MAX_RANGE)
	Laser.Material = Enum.Material.Neon
	Laser.Transparency = 0.5
	Laser.Anchored = true
	Laser.CanCollide = false
	Laser.CanTouch = false
	Laser.Color = Color3.fromRGB(255, 0, 0)
	
	Laser.CFrame = CFrame.lookAt(BulletRayCastPart.Position, EndPosition) * CFrame.new(Vector3.new(0, 0, -MAX_RANGE/2))
	Laser.Parent = game.Workspace
	Debris:AddItem(Laser, 30)
end

PistolFiredEvent.OnServerEvent:Connect(function(player, Origin, Direction, ExcludeList, Missed_End_Position)
	local RayCastParameters = RaycastParams.new()
	RayCastParameters.FilterType = Enum.RaycastFilterType.Exclude
	RayCastParameters.FilterDescendantsInstances = ExcludeList
	RayCastParameters.IgnoreWater = true

	local RayResults = game.Workspace:Raycast(Origin, Direction, RayCastParameters)

	if not RayResults then Laser_Missed(Missed_End_Position) return end
	Laser_Hit(RayResults.Instance, RayResults.Position, RayResults.Distance)

	if not RayResults.Instance.Parent:FindFirstChild("Humanoid") then return end
	local Humanoid = RayResults.Instance.Parent:FindFirstChild("Humanoid")

	if RayResults.Instance.Name == "Head" then
		Humanoid:TakeDamage(15)
	else
		Humanoid:TakeDamage(10)
	end
end)

at first glance I would assume it’s because of the MAX_RANGE and its reaching the cursor position at 200 studs and continues because it doesn’t hit anything

otherwise i’m not really sure

I’m trying to make the laser’s size stretch to the player’s Mouse.Hit.Position within 200 studs when they miss but idk why it’s completely inaccurate??

This CFrame construction seems like it would be fine but I’m not 100% sure about it.
I would try to construct it without doing a matrix multiplication.

local diff = EndPosition - BulletRayCastPart.Position
Laser.CFrame = CFrame.lookAlong(
	EndPosition - diff/2,
	diff,
	Vector3.yAxis
)

Wait, I don’t understand the code. Can you explain it and what do you mean by matrix multiplication?

When you multiply two CFrames it will perform a matrix muliplication since CFrames are matricies.

diff is a vector calculated from BulletRayCastPart.Position to EndPosition which is EndPosition - BulletRayCastPart.Position

The center position can be calculated 3 different ways (that I think of right now):
fromPos + diff/2
toPos - diff/2
(fromPos + toPos)/2

CFrame.lookAlong takes position, lookVector, upVector as the parameters.

Welp, looks like I have to study CFrames more. I don’t know what fromPos, toPos, and probably what EndPosition - BulletRayCastPart.Position gives you (I honestly forgot)

It’s just vector addition & subtraction.


image

In your case,

local fromPos = BulletRayCastPart.Position
local toPos = EndPosition

local diff = toPos - fromPos

-- we know (fromPos + toPos) / 2 is going to give the center
local center0 = (fromPos + toPos)/2


-- what about these two methods?

local center1 = fromPos + diff/2
-- fromPos + (toPos - fromPos)/2
-- = fromPos + toPos/2 - fromPos/2
-- = fromPos - fromPos/2 + toPos/2
-- = fromPos/2 + toPos/2
-- = (fromPos + toPos)/2

local center2 = toPos - diff/2
-- similar proof as above

visually, these also make sense
if you add half the vector to the starting position, you will be at center
if you subtract half the vector from the ending position, you will be at the center

How do I fix the “laser” inaccuracy though when the player hits nothing?

does this happen when you stand still or when you move while shooting?

if it happens only when you move, then it’s because of latency
the amount of ping the client has is the amount of time (in ms) that it takes for the remote event to get received on the server

and since you’re constantly moving on the client, the server creates a laser from the client’s position at the time the event was received, but sets its end position to the hit position that was originally directly infront of the client (straight line)

I’m not sure, I didn’t test it yet but let me do that right now.


It happens during both when I shoot at nil also this didn’t happen before but the lasers started going backwards (the lasers to the side of me)

I think this is a problem that has to do with Mouse.Hit being relative to the origin when nothing is hit. I would try setting the lookAt CFrame to add on EndPosition to the part position:

-- Laser_Missed function
Laser.CFrame = CFrame.lookAt(BulletRayCastPart.Position, BulletRayCastPart.Position + EndPosition) * CFrame.new(Vector3.new(0, 0, -MAX_RANGE/2))

I tested it and it actually solved it…? Wait, but how did adding the BulletRayCastPart.Position + EndPosition solve it though?

You subtracted that position before you sent it to the server.

Isn’t that’s what supposed to happen though? The Direction is the EndPosition - Origin right?

the 4th argument is (Mouse.Hit.Position - Origin)) which on the server is Missed_End_Position
Origin is local Origin = BulletRayCastPart.Position
The solution’s lookAt position is BulletRayCastPart.Position + EndPosition
EndPosition is passed to the function here : Laser_Missed(Missed_End_Position)
Thus EndPosition is actually the direction. You named the direction “Missed_End_Position”

Dang, I didn’t realize that. I didn’t notice at all ;-;