Ray isn't going the direction I want it to

  1. What do you want to achieve?
    I want my ray to go the direction the player is pointing with their mouse while also keeping it a certain distance like 15-20 studs.
  2. What is the issue?
    The ray doesn’t seem to be going the direction the mouse is pointing to but I do know the ray is working since I moved the origin to the point where I want the ray to detect and it ran the rest of the code successfully.

The line where the problem is at:

local raycastResult = workspace:Raycast(rayOrigin, rayDirection*.02, raycastParams)
  1. What solutions have you tried so far?
    I looked on the developer hub but it didn’t give the information I wanted.

Local Script

local player = game.Players.LocalPlayer
local tool = script.Parent
local db = true
local cooldown = 1.25

tool.Activated:Connect(function()
	if db then
		db = false
		local aPosition = tool.Handle.Position
		local mouse = player:GetMouse()
		local rayOrigin = aPosition
		local rayDirection = mouse.Hit.p
		
		local raycastParams = RaycastParams.new()
		raycastParams.FilterDescendantsInstances = {workspace["Spawn Zone"]["Spawn Cuttable Trees"]}
		raycastParams.FilterType = Enum.RaycastFilterType.Whitelist
		local raycastResult = workspace:Raycast(rayOrigin, rayDirection*.02, raycastParams)
		
		if raycastResult then
			local hitPart = raycastResult.Instance
			
			if hitPart.Name == "Meshes/Low Poly Trees_Cylinder" or "Meshes/basic_tree_Sphere (1)" then
				if hitPart.Parent.Name == "Trees" or "TestTrees" then
					hitPart.Parent.Fire:FireServer(tool.Damage.Value)
					wait(cooldown)
					db = true
				end
			end
		else
			print('Nothing hit')
			db = true
		end
	end
	
end)

Position vector is not a direction vector. This is because position vectors start from origin (0,0,0) while directions starts from rayOrigin hence different.

Use the trace back formula to get the new direction.
Start from point B, move along path position vector rB back to origin so -rB and then go along path rA to position A so rA, all together is (-rB + rA)

		local rayOrigin = aPosition
		local rayDirection = (mouse.Hit.p-aPosition).Unit*15
1 Like