Raycast is inaccurate?

So I was using ray cast in a gun, it worked but didn’t. The ray cast is very inaccurate. I could be aiming at a target(with humanoid), and it would take damage but sometimes it doesn’t and says something completely different. I aimed at the target, it took damage and printed it took damage, but when I click again in the exact same spot, it says it something else. I can’t figure out the problem.

Here is the script:

gun = script.Parent
mouse = game.Players.LocalPlayer:GetMouse()

gun.Equipped:Connect(function(mouse)
mouse.Button1Down:Connect(function()

local origin = gun.Firepart.Position
local direction = mouse.Hit.p
local raycastResult = workspace:Raycast(origin, direction)

		if raycastResult then
			
			--Create attachments
			local AttachmentA = Instance.new("Attachment")
			AttachmentA.WorldPosition = origin
			AttachmentA.Name = "AttachmentA"

			local AttachmentB = Instance.new("Attachment")
			AttachmentB.WorldPosition = mouse.Hit.p
			AttachmentB.Name = "AttachmentB"

			--Create beam
			local beam = gun.Firepart.Beam:Clone()
			beam.Attachment0 = AttachmentA
			beam.Attachment1 = AttachmentB
			beam.Parent = game.Workspace
			
			print(raycastResult.Position, raycastResult.Instance)
			
			local hum = raycastResult.Instance.Parent:FindFirstChild('Humanoid')
			if hum then
				hum:TakeDamage(26)
				print("Found Humanoid")
			end
		end
	end)
end)


1 Like

You’re using the second argument of the raycast, direction, incorrectly. It’s not a position in the world to shoot towards, but a direction to travel from the origin. For example if direction was Vector3.new(0,1,0), it would raycast directly upwards.

To get a direction vector from two positions, you can do destination - origin. Now, this vector would have a length of the distance between destination and origin so each raycast would have a different length. To fix this, you can normalize the direction vector (set it to a length of 1 stud) with .Unit, and then multiply that by the max range of the gun. In your case, if the gun is to have a range of say 100 studs, it would look like this:

local origin = gun.Firepart.Position
local destination = mouse.Hit.p
local direction = (destination - origin).Unit * 100
local raycastResult = workspace:Raycast(origin, direction)
3 Likes

thank you bro, i know its been almost 3 years but u’ve helped me