Ray doesnt cast where it should

I have a custom character, more specifically a cube, and i am casting a ray from a part called “muzzle” to the position of the mouse
–muzzle:

And when i click to cast the ray this happens(sorry for the bad quality, but im sure you can understand what’s wrong): Imgur: The magic of the Internet

This is my script:

local pl = game:GetService("Players")
local LocalPL = game.Players.LocalPlayer
local mouse = LocalPL:GetMouse()

local char = LocalPL.Character or LocalPL.CharacterAdded:Wait()

local torso = char:WaitForChild("Torso")

local mouse = LocalPL:GetMouse()

local muzzle = char:WaitForChild("Muzzle")

--scrtipting the cube shooting--

local uis = game:GetService("UserInputService")

if torso.Shape == Enum.PartType.Block then
	
	uis.InputBegan:Connect(function(input)
		
		local mouseIn = input.UserInputType
		if mouseIn == Enum.UserInputType.MouseButton1 and muzzle then
			
			local ray = Ray.new(muzzle.Position, mouse.Hit.Position)
			local hit, position = game.Workspace:FindPartOnRayWithIgnoreList(ray, {torso})
			
			local beam = Instance.new("Part",workspace)
			
			beam.BrickColor = BrickColor.new("Bright red")
			beam.Material = "Neon"
			beam.Transparency = 0.25
			beam.Anchored = true
			beam.Locked = true
			beam.CanCollide = false	
			
			local distance = (muzzle.Position - position).magnitude
			beam.Position = Vector3.new(muzzle.CFrame, position)
			
			if hit then
				
				print(hit.Name)
			else
				print("hit nothing")
				
			end
			
		end
		
	end)
	
end

Thanks for reading and if you could help me i would be thankful
Anyways have a nice day

Could you provide a screenshot of where the ray is going? It might have something to do with the way you’re visualizing it.

i think its in the video Imgur: The magic of the Internet

Oh sorry, I overlooked that. Thank you

The 2nd argument of Ray.new is supposed to be a direction of the end point from the origin, rather than the position of the end point from the origin (0, 0, 0).

Fix:

local Ray = Ray.new(muzzle.Position, (mouse.Hit.Position - muzzle.Position))

The direction can be extended, but it’s not really necessary, by using:
(mouse.Hit.Position - muzzle.Position).Unit * LENGTH

1 Like

Thanks a lot, wouldnt have figured it out on my own