Can't accurately predict raycast trajectory

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.

print distance and bullet.Position and compare , then print direction ,maybe the problem is from there

Sorry I should have been more clear in my post - I know that the destination or ‘point B’ is the issue here, but I have zero idea how to fix it. I’m terrible at vector math. Clearly I’m not recreating the raycast correctly but I don’t know why it doesn’t work.

DrawLine(origin,distance,BrickColor.Red())

Your DrawLine function expects a Vector3 position for the second argument. You’re passing in distance, which is a direction vector. While technically they’re both Vector3s, in context they’re quite different. bullet.Position is a position vector relative to workspace origin, while distance is derived from the gun’s lookVector, which is a unit vector used to denote direction.

It should be:
DrawLine(origin, origin + distance, BrickColor.Red())

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.