Why isn't the raycast working?

local tool = script.Parent

local function shoot()
	local rayOrigin = tool.gun.Position
	local rayDirection
	local rayTarget = tool.Parent.Humanoid.TargetPoint
	--Do a CFrame operation to determine the orientation to that point
	local operationPart = Instance.new("Part")
	operationPart.Transparency = 1
	operationPart.CanCollide = false
	operationPart.Anchored = true
	operationPart.CFrame = CFrame.new(rayOrigin, rayTarget)
	--Destroy the Operation Part, and cast the ray
	rayDirection = operationPart.Orientation
	print(rayDirection)
	print(rayOrigin)
	operationPart:Destroy()
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {tool.Parent}
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)
	
	
	if raycastResult then
		local hitPart = raycastResult.Instance
		if hitPart:IsA("Part") then hitPart.BrickColor = BrickColor.Random() end
	end
	
end
tool.Activated:Connect(shoot)

It’s supposed to change the BrickColor of any Part it hits. It used to work, but once I added the CFrame operation, it doesn’t work anymore.

local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)

Try doing rayDirection * magnitude and supply a magnitude value. Such as 500, or however far you want the ray to go.

local raycastResult = workspace:Raycast(rayOrigin, rayDirection * 500, raycastParams)
1 Like

A much simpler way to find the direction you want to give the ray, without all the complicated creation of parts and such, is a simple vector subtraction. Instead of all that code with operationPart, you can simply do rayDirection = (rayTarget - rayOrigin).Unit (and then multiply it by a magnitude as mentioned in the reply above mine)

1 Like

Still not working, no errors though :confused:

EDIT: Wait, what is the magnitude measured in? Studs, or pixels?

@cowsoncows It also seems to work on one part below me, not where my mouse is.

The magnitude is in studs.
Taking a look at TargetPoint's documentation, Roblox recommends to avoid using it entirely because it doesn’t work anymore.

Instead you should separate this into two parts. A LocalScript will handle the input, detecting when the player clicks with the tool equipped, then sends the mouse information over to the server via RemoteEvent in order to have the server do the raycast and hit detection.

2 Likes