Inaccurate Reflections

I need help with an accurate reflection

When the reflective ray bounces off of a surface, then the next ray angles slightly downward

I have already checked that the equation was accurate, and looked over my code

I have not found any code that changes the angles purposefully

local function reflect(vector, normal)--creds egomoose for math
	return -2 * vector:Dot(normal) * normal + vector;
end

function nex(frame,new,hit,pos,norm)
	--print(amnt)
	local calc = new
	if hit then
		local ref = reflect((new).Position-frame.Position,norm)
		calc = CFrame.new(frame.Position)*CFrame.new(Vector3.new(0,0,0),ref)
	end
	return calc,pos
end

function line(a,b)
	local new = Instance.new("Part")
	new.Parent = script.Parent.Parent.Rays
	local mag = (a-b).Magnitude
	--local pos = (a*(1-0.5))+b*0.5
	new.Size = Vector3.new(.1,.1,mag)
	new.Anchored = true
	new.CanCollide = false
	new.Material = Enum.Material.Neon
	new.Color = Color3.new(1,0,0)
	new.CFrame = CFrame.new(a,b)*CFrame.new(0,0,-mag/2)
end

while game:GetService("RunService").Stepped:Wait() do
	local all = workspace.Lazer.Rays:GetChildren()
	for i = 1,#all do
		all[i]:Destroy()
	end
	
	local frame = script.Parent.CFrame
	
	for i = 1,100 do
		local to = (frame*CFrame.new(0,0,-100)).Position
		local vec = to-frame.Position
		local ray = Ray.new(frame.Position,vec)
		local hit,pos,norm = workspace:FindPartOnRayWithIgnoreList(ray,{script.Parent.Parent})
		local frame2
		
		--vec = vec/Vector3.new(math.abs(vec.X),math.abs(vec.Y),math.abs(vec.Z))
		
		if hit then
			to = pos
			
			local ref = reflect(vec,norm)
			frame2 = CFrame.new(pos,ref)
		end
		line(frame.Position,to)
		
		if frame2 then
			frame = frame2
		else
			break
		end
	end
end

An older tutorial but still valid.

1 Like

I already resolved the problem, and found out that

frame2 = CFrame.new(pos,ref)

should’ve been

frame2 = CFrame.new(pos,pos+ref)