How do I fix this Raycast?

I’ve been doing random stuff in my freetime, and this includes recreating a pre-existing gun kit. For some reason, this raycast does not go where i want it to. How do I fix this?
VIDEO OF WHAT HAPPENS:

SCRIPT:

function FireFunction(dir,pla)
	local raypar = RaycastParams.new()
	raypar.FilterDescendantsInstances = {pla.Character,workspace.GunEffect}
	raypar.FilterType = Enum.RaycastFilterType.Blacklist
	local part1x = Instance.new("Part",workspace.GunEffect)
	part1x.Anchored = true
	part1x.CanCollide = false
	part1x.Transparency = 0.4
	part1x.Size = Vector3.new(0.8,0.8,0.8)
	part1x.Position = dir
	game.Debris:AddItem(part1x,0.45)
	local rayc = workspace:Raycast(pla.Character.Head.Position, dir,raypar)
	if rayc then
		local part1 = Instance.new("Part",workspace.GunEffect)
		part1.Anchored = true
		part1.CanCollide = false
		part1.Transparency = 1
		part1.Size = Vector3.new(0.1,0.1,0.1)
		part1.Position = script.Parent.Handle.Position
		local part2 = Instance.new("Part",workspace.GunEffect)
		part2.Anchored = true
		part2.CanCollide = false
		part2.Transparency = 1
		part2.Size = Vector3.new(0.1,0.1,0.1)
		part2.Position = rayc.Position
		local attachment2 = Instance.new("Attachment",part2)
		local attachment1 = Instance.new("Attachment",part1)
		local gunbeam = script.Parent.Handle.GunBeam:Clone()
		gunbeam.Parent = part1
		gunbeam.Attachment0 = attachment1
		gunbeam.Attachment1 = attachment2
		game.Debris:AddItem(gunbeam,0.45)
		game.Debris:AddItem(part1,0.45)
		game.Debris:AddItem(part2,0.45)
	end

end
1 Like

It is probably something wrong with the dir variable. Could you show us how you calculated it?

It looks to me like your shooting it at mouse.Target instead of mouse.Hit.Position.

I left my house but no, dir is Mouse.Hit.Position

Mouse.Hit already gives you a position so no need for Mouse.Hit.Position

According to the API, mouse.Hit gives you a CFrame…

Are part1 and part2 in the positions that they are supposed to be?

I’ll make them visible real quick to see.

Part2 is not in the right place, not even close to the mouse position.

Afaik, you’re using a Position as the direction of the ray. Raycasts only accept unit/normal directional vectors. To convert your position to a unit/normal, simply append “.Unit” to it (like mouse.Hit.Unit)

However, this will most likely do nothing because we haven’t set how far we want this ray to go. Multiply the unit value (like .Unit * 80) so the raycast knows to go 80 studs in whatever the direction is. There are also properties like LookVector, which is the front normal of a CFrame.

Keep in mind, you can only use mouse.Hit for these operations, not mouse.Hit.Position

Fixed it using LookVector. Thank you!

Try this.

--Replace 
local rayc = workspace:Raycast(--yourstuff)

--with

local rayc = workspace:Raycast(Mouse.UnitRay.Origin,Mouse.UnitRay.Direction * 1000)