Raycast just isn't going to the right mouse position

Hello. I’m having a hard time figuring out why my Raycast isn’t going exactly where the mouse is pointed. I did raycasts before and they always worked as intended, but right now they just don’t seem to be doing it right.
image
The raycast does move with the mouse, but its end position isn’t on the mouse, and it seems to move even further away as my character walks away from the center of the map.

Below’s the code for generating my raycast:

player.CharacterAdded:Connect(function(char)

	workspace.Raycasts:ClearAllChildren()
	local mouse = player:GetMouse()

	runservice.RenderStepped:Connect(function()
		local hrp = char:FindFirstChild("HumanoidRootPart")
		local origin = hrp.Position
		local direction = mouse.Hit.Position

		local raycastParams = RaycastParams.new()
		raycastParams.FilterType = Enum.RaycastFilterType.Exclude
		raycastParams.FilterDescendantsInstances = {player.Character}

		local result = workspace:Raycast(origin, direction, raycastParams)

		local intersection = result and result.Position or origin + direction
		local distance = (origin - intersection).Magnitude

		local closest = {potential = nil, distance = math.huge}

		local bullet_clone = storage.Bullet:Clone()
		bullet_clone.Size = Vector3.new(0.1, 0.1, distance)
		bullet_clone.CFrame = CFrame.new(origin, intersection)*CFrame.new(0, 0, -distance/2)
		bullet_clone.Transparency = 0

		runservice.RenderStepped:Connect(function()
			if bullet_clone then bullet_clone:Destroy() end
		end)
	end)
end)

I’m left to wonder why this is happening. Is it just the visualizer that’s coded wrong, or is the raycast actually going the wrong place? How can I fix this? Thanks in advance.

Edit note 1: The raycast doesn’t seem to angle itself by the Y vector, only X and Z.

Raycast Direction needs to be a LookVector, to fix this you can do

Direction = CFrame.new(Origin, MousePos).LookVector * RayLength

You can also change the Origin (but make sure to use the code snippet above) to the Camera Position to avoid perspective issues (raycast looking like it’s not exactly at the mouse, or slight offset)

1 Like

Thank you. Setting the direction to the LookVector solved it and also allowed me to apply the range limit to the raycast.

You can also change the Origin to the Camera Position to avoid perspective issues

I’ll keep that in mind, though the raycast is supposed to originate from the humanoid root part in this situation.

You can Set the Raycast Origin to the Camera Position, and then create the bullet, raypart, or whatever it is spawn from the HumanoidRootPart Position instead of the Raycast Origin, basically making 2 Separate Variables for the Origin. Raycast Origin, and the Bullet Origin

1 Like