Raycast gun problem

I’m working on a isometric angled shooter game but I encountered a problem.

I am using raycast for the firing system and every time I fire it, the raycast won’t detect the character when it is clicked onto the character itself. It only works when it is fire somewhere else and the raycast intersects the NPC. I don’t know what I’m doing wrong please this is my second time using raycast.

Local Script (For mouse position):

local mouse = player:GetMouse()

local tool = script.Parent
local fireEvent = tool.fire

mouse.Button1Down:Connect(function()
	fireEvent:FireServer(mouse.Hit.Position)
end)

Server Script (Raycast part):

fireEvent.OnServerEvent:Connect(function(player, position)
	local params = RaycastParams.new()

	params.FilterType = Enum.RaycastFilterType.Exclude
	params.FilterDescendantsInstances = {player.Character}

	local raycast = workspace:Raycast(location.Position, position, params)
	
	local visualizedPart = Instance.new("Part",workspace)
	visualizedPart.CanCollide = false
	visualizedPart.Size = Vector3.new(0.1,0.1,0.1)
	visualizedPart.Position = position
	visualizedPart.Material = Enum.Material.Neon
	visualizedPart.Color = Color3.new(1, 1, 1)
	visualizedPart.Anchored = true
	
	if raycast and raycast.Instance then
		print(raycast.Instance.Name)
		
		local distance = (location.Position - raycast.Position).Magnitude
		local p = Instance.new("Part", workspace)
		p.Anchored = true
		p.CanCollide = false
		p.Size = Vector3.new(0.1, 0.1, distance)
		p.CFrame = CFrame.lookAt(location.Position, position)*CFrame.new(0, 0, -distance/2)
		
		if raycast.Instance.Parent:FindFirstChildOfClass("Humanoid") then
			local hum = raycast.Instance.Parent:WaitForChild("Humanoid")
			hum:TakeDamage(statsFolder.damage.Value)
			visualizedPart.Color = Color3.new(1, 0, 0)
		elseif raycast.Instance.Parent.Parent:FindFirstChildOfClass("Humanoid") then
			local hum = raycast.Instance.Parent.Parent:WaitForChild("Humanoid")
			hum:TakeDamage(statsFolder.damage.Value)
			visualizedPart.Color = Color3.new(1, 0, 0)
		end
	end
end)

Video to show what I meant:

4 Likes

Note: Sometimes doing what I said to detect the NPC wouldn’t even work.

You’re experiencing the consequences of a common misconception about the functionality of WorldRoot:Raycast. The second argument does not represent the endpoint of the ray. It instead represents the direction from the origin the ray shall travel:

The direction to a particular position from a set origin can be calculated as:

local direction = destination - origin

Therefore:

local origin = location.Position
local direction = position - origin
local raycast = workspace:Raycast(origin, direction.Unit * RAY_LENGTH, params)
2 Likes

Thank you so much! It works way better now. I’m not really experienced in scripting (especially raycast) so this saved my game

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.