I was trying to make a gun from scratch and started simple by using a raycast for the bullet trajectory. I also wrote a function that SHOULD accurately draw the bullet path, but something here isn’t quite working as it should…
local tool = script.Parent
local gun = tool.Handle
local RAYCAST_LENGTH = 100
local DAMAGE = 10
local function DrawLine(A,B,color)
local line = Instance.new("Part")
line.Parent = workspace
line.CanCollide = false
line.Anchored = true
line.CastShadow = false
line.BrickColor = color
local Center = (A + B) / 2
line.CFrame = CFrame.new(Center, A)
line.Size = Vector3.new(0.1,0.1,(A-B).Magnitude)
task.spawn(function()
while task.wait() do
line.Transparency += .01
if line.Transparency >= 1 then
line:Destroy()
break
end
end
end)
end
local function onActivate()
local direction = gun.CFrame.LookVector
local distance = direction * RAYCAST_LENGTH
local origin = gun.Attachment.WorldCFrame.Position --attachment is aligned with end of barrel
DrawLine(origin,distance,BrickColor.Red())
local bullet = workspace:Raycast(origin,distance)
if bullet then
DrawLine(origin,bullet.Position,BrickColor.Green())
if bullet.Instance.Parent:FindFirstChildWhichIsA("Humanoid") then
bullet.Instance.Parent:FindFirstChildWhichIsA("Humanoid").Health -= DAMAGE
end
end
end
I’ve inserted the DrawLine function at two points: one that predicts the bullet trajectory (colored red) and one that traces the ‘actual’ bullet trajectory based on the raycast results (green). This is what it looks like when I fire the gun:
For some reason the red line is always crooked no matter what. Since the green line is always straight I assume the issue isn’t with the DrawLine function but everything else seems perfectly fine. What exactly am I doing wrong here?
Also not super related but the green line only appears sometimes, even if the raycast would have clearly hit something right in front of it.
