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.
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.