How would I fire a raycast from the player's head?

I am trying to fire a raycast from the player’s head. This is the code I wrote.
It only fires in one direction rather than from where the player’s head is pointing.

local Character = script.Parent

function fireRay()
	local IgnoreCharacter = Character
	while wait(2) do
		local Ray = Ray.new(Character.Head.CFrame.p,Vector3.new(100,0,0)) -- I believe its this part
		local part = workspace:FindPartOnRay(Ray,IgnoreCharacter )
		if part then
			print(part.Name)
			if part.Name == "RayTest" then
				print("correct part!")
			end
		end
	end
end

while true do
	
	wait(1)
	fireRay()
	
end

try doing this:
local Ray = Ray.new(Character.Head.CFrame.p, Character.Head.CFrame.LookVector * Vector3.new(100,0,0))

https://gyazo.com/c0def36ca2505fd910ff3c7b655f12eb
The ray goes in some weird directions.

could you show me what weird directions from 3rd person perspective?
please

Here:
https://gyazo.com/f4989dd7acf8b08098ee99e96412a74c

  1. FindPartOnRay is deprecated
  2. The directional component of the ray is the LookVector of the head
local Char = game.Players.LocalPlayer.Character

local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
raycastParams.FilterDescendantsInstances = {Char}
raycastParams.IgnoreWater = true
 
local raycastResult = workspace:Raycast(Char.Head.Position, Char.Head.CFrame.LookVector*50, raycastParams)
 
local hitPart, hitPosition = unpack({raycastResult.Instance, raycastResult.Position})
6 Likes

Your code errors at line

	local hitPart, hitPosition = unpack({raycastResult.Instance, raycastResult.Position})

attempt to index nil with ‘Instance’

i saw the problem…
local Ray = Ray.new(Character.Head.CFrame.p, Character.Head.CFrame.LookVector * Vector3.new(100,100,100))

hopefully this time it works

1 Like

Disregard, added a wait at the start and it works great.

If the ray didnt intersect with something it is nil, so you should do:

if raycastResult then
--code
end
1 Like