Dot Product not working

  1. What do you want to achieve? Keep it simple and clear!

I’m trying to use Dot Product to detect when a player is in the field of vision of an NPC.

  1. What is the issue? Include screenshots / videos if possible!

On line 7, the code displays “Players.ChrisCraft771.PlayerScripts.NightMareView:7: attempt to index nil with ‘Head’”

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I was unable to think of any potential solutions to this issue.

local RunService = game:GetService("RunService")

local npc = workspace.The_NightMare
local character = game.Players.LocalPlayer.Character

RunService.RenderStepped:Connect(function()
	local npcToCharacter = (character.Head.Position - npc.Head.Position).Unit -- This is the line of code which breaks
	local npcLook = npc.Head.CFrame.LookVector
	
	local dotProduct = npcToCharacter:Dot(npcLook)
	
	if dotProduct > .4 then
		-- in view
	else
		-- not in view
	end
end)

The character might not be loaded yet. Try this:

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()

I edited the code and that was the solution. Thanks for helping me out!

1 Like