So I just made a gun that projects bullets using RayCasting.
[EDIT]
I’ve decided to take my code apart and show the first position of the bullet, and then a second position marked by two red parts. I tried to find the parts on the ray between these two, and for the majority of the time, nothing printed, and I’m wondering if I’m using the functions incorrectly.
Here is my code:
mouse.Button1Down:Connect(function()
local ray = Ray.new(gun.Nuzzle.CFrame.p, (mouse.Hit.p - gun.Handle.CFrame.p).unit * 5)
local part, position = workspace:FindPartOnRay(ray, char, false, true)
local beam = Instance.new("Part", workspace)
beam.BrickColor = partColor
beam.FormFactor = "Custom"
beam.Material = "Neon"
beam.Transparency = 0
beam.Anchored = true
beam.Locked = true
beam.CanCollide = false
local distance = (gun.Nuzzle.CFrame.p - position).magnitude
beam.Size = Vector3.new(0.1, 0.1, distance)
beam.CFrame = CFrame.new(gun.Nuzzle.CFrame.p, position) * CFrame.new(0, 0, -distance / 2)
if part then
game:GetService("Debris"):AddItem(beam, .05)
local humanoid = part.Parent:FindFirstChild("Humanoid")
if not humanoid then
humanoid = part.Parent.Parent:FindFirstChild("Humanoid")
end
if humanoid then
gunAction.Damage:FireServer(humanoid)
end
end
game:GetService("RunService").Heartbeat:wait()
if beam == nil then return end
local mark1 = game.ReplicatedStorage.mark:Clone()
mark1.Parent = game.Workspace
mark1.CFrame = beam.CFrame*CFrame.new(0, 0, -2.5)
local mark2 = game.ReplicatedStorage.mark:Clone()
mark2.Parent = game.Workspace
mark2.CFrame = beam.CFrame*CFrame.new(0, 0, -7.5)
local rayo = Ray.new(mark1.CFrame.p, mark2.CFrame.p)
local parto, positiono = workspace:FindPartOnRay(rayo, char, false, true)
if parto then print(parto.Name.." belongs to "..parto.Parent.Name) end
end)
Any help is appreciated <3