Today, I have been trying to experiment with raycasting and was trying to make a laser beam that points to the direction of the raycast and updates itself to point to the new direction whenever the part is turned. The origin of the raycast is the Part, and the direction is the lookVector of the part times 50 studs.
local function MakeRayVisible(ray)
local midpoint = ray.Origin + ray.Direction/2
local Attachment0 = Instance.new("Attachment", game.Workspace.Part)
local Attachment1 = Instance.new("Attachment", game.Workspace.Part)
local Beam = Instance.new("Beam", game.Workspace)
Beam.Color = ColorSequence.new(Color3.fromRGB(170, 0, 0))
Beam.Width0 = 0.2
Beam.Width1 = 0.2
Beam.Attachment0 = Attachment0
Beam.Attachment1 = Attachment1
Attachment0.Position = Vector3.new(0,0,0)
Attachment1.Position = Vector3.new(0, 0, -ray.Direction.magnitude) --I don't know why it is backwards
wait(10) --Why does it beam updating according to the parts direction even with this wait
Beam:Destroy()
Attachment0:Destroy()
Attachment1:Destroy()
end
local part = game.Workspace.Part
while true do
local origin = part.Position
local direction = part.CFrame.LookVector * 50
local ray = Ray.new(origin, direction)
MakeRayVisible(ray) --The while loop only restarts after the function is complete, which takes 10 seconds
print("Ray updated.")
end
The beam does change its direction based on the rotation of the part and it is working as it is intended. My question is however, how does this even work properly, can someone please explain how my code works for some reason?
