You need to reject the point from the ray. I wrote this simple demonstration to showcase how it can be implemented on Roblox when we have to take into account that the ray doesn't start from (0, 0, 0).
Pardon me for possibly wrong terminology. I'd appreciate if somebody could look at it and clean up the math part. The equations may not be in their clearest form.
local part = workspace.Part
local RunService = game:GetService("RunService")
local rayOrigin = Vector3.new(-20, 0, -20)
local rayDir = Vector3.new(0, 1, 1)
local rayLen = 100
local function drawPoint(v3, p)
p = p or Instance.new("Part")
p.Anchored = true
p.BrickColor = BrickColor.Red()
p.Size = Vector3.new(2, 2, 2)
p.CFrame = CFrame.new(v3)
p.Parent = workspace
return p
end
local function drawRay(ray)
local p = Instance.new("Part")
p.Anchored = true
p.BrickColor = BrickColor.Green()
p.CFrame = CFrame.new(ray.Origin, ray.Origin + ray.Direction) * CFrame.new(0, 0, -ray.Direction.Magnitude / 2)
p.Size = Vector3.new(1, 1, ray.Direction.Magnitude)
p.Parent = workspace
return p
end
local function getRayClosestPoint(ray, point)
local a, b = ray.Origin - point, ray.Direction
local v = a - ((a:Dot(b)) / (b:Dot(b))) * b
return point + v
end
local ray = Ray.new(rayOrigin, rayDir * rayLen)
drawRay(ray)
local point = getRayClosestPoint(ray, part.Position)
local pointPart = drawPoint(point)
RunService.Stepped:Connect(function()
point = getRayClosestPoint(ray, part.Position)
drawPoint(point, pointPart)
end)
3 comments
it also only seems to work when the ray is pointed away from the part
the function is broken. what r u trying to do exactly
@theluaBanana like I said, trying to find the closest point on a ray to a part in the workspace. the only other method I know of is using dot product but thats giving me trouble too