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)