Worspace:Raycast returning nil

Hey developers,

I need some help with this code:

local player = game.Players.LocalPlayer	
local mouse = player:GetMouse()
local character = player.Character
local humanoid = character.HumanoidRootPart

local origin1 = humanoid.Position
local mousePos = mouse.Hit.p
local direction1 = (mousePos - origin1).Unit * 30

local function createBeam(origin, direction)
	
	local midpoint = origin + direction/2
	
	local part = Instance.new("Part")
	part.Parent = workspace
	part.Anchored = true
	part.CanCollide = false
	
	part.Material = Enum.Material.Neon
	part.BrickColor = BrickColor.new("Light blue")
	
	part.CFrame = CFrame.new(midpoint, origin)
	part.Size = Vector3.new(.5,.5, direction.magnitude)
	
	wait(0.1)
	part:Destroy()
end

function shootRay(origin, direction)
	local result = workspace:Raycast(origin, direction)
	
	if result then
		
		createBeam(origin, direction)
		
		if result.Instance.Name == "Humanoid" then
			return true
		else
			return false
		end
	end
end

while true do
	result = shootRay(origin1, direction1)
	print(result)
	wait(0.1)
end

This is a local script, and it always returns nil, any ideas?

Btw: the beam part doesn’t even happen

Im still getting “nil” as a result, and no parts are being created

The raycast function returns nil when it doesn’t hit a part, so there might be something wrong with the given direction.

Your code doesn’t work because origin1, mousePos and direction1 variables are outside the loop so their value doesn’t change every time loop runs.
Move those variables inside loop like this:

while true do
	local origin1 = humanoid.Position
	local mousePos = mouse.Hit.p
	local direction1 = (mousePos - origin1).Unit * 30
	print(result)
	result = shootRay(origin1, direction1)
	game:GetService("RunService").RenderStepped:Wait() --Changed wait(0.1) with this because it's more efficient.
end

3 Likes

In my opinion you don’t need to use raycast in this situation. Just use the Mouse.Target to see if there is part. If so then create a beam from the original position to the Target’s position.

The reason he uses raycast is because he wants to limit his beams range which is why (mousePos - origin1).Unit * 30 exists in his code so beams range can be limited to only 30 studs.

2 Likes

Yes it will, be more efficient using that but what will happen if is an expensive function? See what I mean. Maybe he should use the custom wait module which uses RunService.