Ray gets longer the farther I walk away from my spawn point?

So, what I am trying to do is create a ray from either the players camera or the players humanoid root part, and I made a previous script that offset the camera in front of the player, and you can walk close to a wall and your camera clips through it. I tried to fix this problem by trying to cast a ray 5 studs in front of your camera/ root part. However, the farther zoom out or walk away from my spawn point. The ray gets longer. I visualized this by putting a part the same direction as the ray. This might seem confusing with the way I worded things, but anything helps.




local runservice = game:GetService("RunService")

local part = Instance.new("Part")
part.Anchored = true
part.CanCollide = false
part.Parent = workspace

runservice.RenderStepped:Connect(function()
    local mouse = game.Players.LocalPlayer:GetMouse()
    local RP = game.Players.LocalPlayer.Character.HumanoidRootPart
    local ray = Ray.new(RP.Position, RP.Position +  (RP.CFrame.LookVector * 10) )
    local midpoint = (ray.Origin + ray.Direction)/2
    part.CFrame = CFrame.lookAt(midpoint, ray.Origin)
part.Size = Vector3.new(1, 1, ray.Direction.Magnitude)
    local part = workspace:FindPartOnRayWithIgnoreList(ray,{script.Parent})
print(part)
end)

Your issue is you are adding RP.Position (ray origin) to the ray direction, this makes sense for CFrame.new(position, lookAt), but this is not the same for rays, this would be more accurate:

-- Removed RP.Position from the second parameter.
Ray.new(RP.Position, RP.CFrame.LookVector * 10)

Also, you’re using deprecated Ray API, you should use the new API, which for you would look something like this:

local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {script.Parent} -- Your ignore list.

local raycastResult = workspace:Raycast(RP.Position, RP.CFrame.LookVector * 10, raycastParams)

if raycastResult then -- Raycast hit something.
    local part = raycastResult.Instance -- Get the hit part.
    print(part)
end
3 Likes