Raycast to mouse position and camera script not cooperating

As shown in the video, my Raycasting script works fine at distances but goes wonky when close to an object.

I’ve tried messing with the mouse.hit and other mouse functions, but to no avail.

Please help.

Local script:

local ray = Ray.new(tool.Handle.CFrame.p, (mouse.Hit.p - tool.ShootPoint.CFrame.p).unit*300)
local hit, position, normal = game.Workspace:FindPartOnRay(ray, char)

local distance = (position - tool.ShootPoint.CFrame.p).magnitude
local rayPart = Instance.new(“Part”, workspace)
rayPart.Anchored = true
rayPart.Name = “RayPart”
rayPart.BrickColor = BrickColor.new(“Bright yellow”)
rayPart.Transparency = 0.5
rayPart.Material = “Neon”
rayPart.CanCollide = false
rayPart.TopSurface = Enum.SurfaceType.Smooth
rayPart.BottomSurface = Enum.SurfaceType.Smooth
rayPart.formFactor = Enum.FormFactor.Custom
rayPart.Size = Vector3.new(0.05, 0.05, distance)
rayPart.CFrame = CFrame.new(position, tool.Handle.CFrame.p) * CFrame.new(0, 0, -distance/2)

1 Like

This is usually something that happens when you use the PlayerMouse object to determine the end point of a cast. You should instead make use of the function Camera.ViewportPointToRay, which will return a unit ray from the camera in the direction of where the mouse is located. You can then use the origin over mouse.Hit.p (by the way, CFrame.p is deprecated in favour of CFrame.Position).

Other than that, small advisory of the way you create the ray visualisation part: don’t use the parent argument on Instance.new.