local tool = script.Parent local player = game.Players.LocalPlayer tool.Equipped:Connect(function(mouse) mouse.Button1Down:Connect(function() local ray = Ray.new(tool.Handle.CFrame.p,(mouse.Hit.p - tool.Handle.CFrame.p).unit * 300) -- Why use p instead of Position? local part, position= game.Workspace:FindPartOnRay(ray,player.Character,false,true) -- does this define both, the player that got hit and the position of that player? local beam = Instance.new("Part",tool) beam.Material = "SmoothPlastic" beam.Transparency = 0.5 beam.Anchored = true beam.CanCollide = false beam.Locked = true local distance = (tool.Handle.CFrame.p - position).magnitude -- Purpose of magnitude? beam.Size = Vector3.new(0.3, 0.3, distance) -- Purpose of distance on the z-axis? beam.CFrame = CFrame.new(tool.Handle.CFrame.p, position) * CFrame.new(0,0,-distance/2) -- What does the -distance/2 on the z-axis do? if part then local hum = part.Parent:FindFirstChild("Humanoid") if not hum then local hum = part.Parent:FindFirstChild("Humanoid") -- is this line necessary? end if hum then hum:TakeDamage(15) end end game:GetService("Debris"):AddItem(beam,0.5) end) end)
I've put the questions next to the lines of code that i need help with.
CFrame.p
and CFrame.Position
are identical, though the former is deprecated in favour of the latter.
Workspace:FindPartOnRay
returns the BasePart hit and the Vector3 point of intersection (the precise position (in world space) that the Ray hit). This could be useful to know where to place a bullet hole, for example.
Vector3.Magnitude
returns the magnitude/distance of a Vector3 (as a number). In this case, it is used to get the distance between the Tool's handle and the point of intersection.
The distance variable, which we previously worked out is the distance between the Tool's handle and the point of intersection, is used as the Z component of beam's Size. This will make beam stretch the entire distance (with the correct direction and position, which we see later) between the Tool's handle and the point of intersection.
The -distance/2
is offsetting beam so that it starts at the Tool's handles CFrame on the Z axis.
This line appears to be unnecessary. I would return from the function instead to avoid pointless if statements later down the line.