Hello everyone.
I’ve been doing a lot of things involving raycasting recently, but one thing that’s been bugging me recently is how raycasting can become imprecise far from the world’s center.
As shown below:
(Near world origin - so far, so good…)
(Far from world origin - not so good now.)
I’d like to know - is this a problem with the Roblox engine itself, or my code?
My code being:
local function GetReflectedNormal(RayNormal, SurfaceNormal)
-- using formula r = d - 2(d ⋅ n)n
return RayNormal - (2 * RayNormal:Dot(SurfaceNormal) * SurfaceNormal)
end
local RayParams = RaycastParams.new()
RayParams.FilterType = Enum.RaycastFilterType.Blacklist
RayParams.FilterDescendantsInstances = {workspace.LaserPointer}
local function CastLightRay(Origin, Direction, LightBounces, Wavelength)
local LightRayTable = {}
for CurrentLightBounce = 1, LightBounces do
local LightRay = workspace:Raycast(Origin, Direction, RayParams)
if not LightRay then
LightRayTable[CurrentLightBounce] = {Origin = Origin, Direction = Direction}
break
else
LightRayTable[CurrentLightBounce] = {Origin = Origin, Direction = LightRay.Position}
Direction = GetReflectedNormal(CFrame.lookAt(Origin, Direction).LookVector, LightRay.Normal) * 5000
Origin = LightRay.Position
end
end
return LightRayTable
end
local gizmo = require(game.ReplicatedStorage.gizmo)
gizmo.setScale(5)
local function VisualiseLightRay(LightRayTable)
for i, v in pairs(LightRayTable) do
gizmo.drawLine(v.Origin, v.Direction)
end
end
game:GetService("RunService").Heartbeat:Connect(function()
gizmo.clear()
VisualiseLightRay(CastLightRay(
workspace.LaserPointer.EmitPoint.Position,
workspace.LaserPointer.EmitPoint.CFrame:ToWorldSpace(CFrame.new(-5000, 0, 0)).Position,
48))
end)
(gizmo
- visualisation library by @Arbeiters, very cool, 10/10)
(workspace.LaserPointer
- model consisting of:
)
Thanks for any help.