Raycast is hitting unexpected positions

I want to make a gun script with raycasting but the raycast isn’t doing what I thought it would.
It is going in random directions that don’t match up with the mouse’s position at all.

here is my code:

local function createEffects(position)
	local Part = Instance.new("Part", Tool)
	local Att1 = Instance.new("Attachment", Part)
	
	game:GetService("Debris"):AddItem(Part, 0.5)
	Part.Position=position
	Part.Transparency=1
	Part.CanCollide=false
	Part.Anchored=true
	Att1.WorldPosition=Part.Position
	
	Beam.Attachment1=Att1

	Tool.Barrel.ParticleEmitter.Enabled=true
	wait(0.5)
	Tool.Barrel.ParticleEmitter.Enabled=false
end

local function shoot(plyr, mpos)
	local ray = Ray.new(script.Parent.Barrel.Position, mpos)
	local hit, position = workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent.Parent, script.Parent})
	
	if hit then
		local Humanoid = hit.Parent:FindFirstChild("Humanoid")
		if Humanoid then
			Humanoid:TakeDamage(25)
		end
		
		createEffects(position)
	end
end

script.Fire.OnServerEvent:Connect(shoot)
3 Likes

First off, the beam is attached to a part, and you set the part’s position once in the beginning of the script. Therefore no matter which direction you face the beam will keep going to that single location. Secondly, could you proved the code that fires the remote event so that we can see how you calculate the position of the beam.

2 Likes

Your direction is wrong. mpos should not be a position but a direction. Directions can be calculated by

(lookAtPosition - originPosition).unit

Then you can multiply a distance against it.

5 Likes

here is the localscript that fires the event

local Tool = script.Parent
local Fire = Tool.Script.Fire

Tool.Equipped:Connect(function(Mouse)
	Mouse.Button1Down:Connect(function()
		Fire:FireServer(Mouse.Hit.p)
	end)
end)
3 Likes

Ok I will try that and see what happens

2 Likes

The problem is that say your mouse is pointing at a wall that is 20x10 meters long, it will make the beam point to the center of that wall even though your mouse might be pointing toward the edge of the wall.

1 Like

When I change it to that it does absolutely nothing

local ray = Ray.new(script.Parent.Barrel.Position, (mpos - script.Parent.Barrel.Position).unit)

Maybe i did something wrong?
Edit: I didn’t multiply it at all, this works thanks

2 Likes

Yeah I know that but my mouse isn’t even pointing at any of those walls.

2 Likes

The problem is that once the remote event fires, the beam keeps pointing at the same wall, it doesn’t know to change it’s direction. I don’t know how to fix this other than constantly firing the server with the mouses updated position, but that could cause lag.

1 Like