Raycast returning nil despite instance in range


The script:

script.Parent.Activated:Connect(function()
	if db == false then 
		db = true
		Flash.Enabled = true
		FlashEffect.Visible = true
		Handle.FireSound:Play()
		local camera = workspace.CurrentCamera
		local length = 1000
		local unitRay = camera:ScreenPointToRay(0,0)
		local ray = workspace:Raycast(unitRay.Origin, unitRay.Direction * length)
		if ray then
			script.Parent.Damage:FireServer(ray.Instance)
		end
		wait()
		Flash.Enabled = false
		FlashEffect.Visible = false
		wait(0.4)
		db = false
	end
end)

I think the problem is that you have to use half of the screens pixel size, not 0,0

Dunno for sure though I don’t use screenpointtoray all that often

1 Like

Use Mouse coordinates.

local Players = game:GetService("Players")

local player = Players.LocalPlayer
local mouse = player:GetMouse()
local camera = workspace.CurrentCamera

script.Parent.Activated:Connect(function()
    print(camera:ScreenPointToRay(mouse.X, mouse.Y))
end)

If the shot is not in the exact position of the mouse, then use :ViewportPointToRay() instead.