Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How can I modify this script so that It damages players when looking at It?

Hi!

As the title says, I want to modify this to It damages players but only when you look at It

Script:

script.Parent.Touched:Connect(function(hit)
	local humanoid = hit.Parent:FindFirstChildWhichIsA("Humanoid")
	if humanoid then
		humanoid:TakeDamage(20)
	end
end)

1 comment

0

Use WorldToViewportPoint to first check if it's on-screen at all, and then raycast from that position toward the object to see if it hits anything. If both checks pass then the player is looking at the part

1 answer

You can use Vector3:Dot() to tell whether the position of PartB is within the FOV of PartA's LookVector. Basically, it returns a negative when it is behind the part and returns to a positive when it is in front of it.

There's a YouTube tutorial and a DevForum post about it and it might be simpler than my explanation.

local NPC = workspace.NPC -- for this example we have a dummy character named "NPC"

local sightLimit = 0.7071 -- from 0 to 1; you can edit this until you get the result you wanted

game:GetService("Players").PlayerAdded:Connect(function(Player)
	Player.CharacterAdded:Connect(function(Character)
		local Head = Character:WaitForChild("Head")
		local Humanoid = Character:WaitForChild("Humanoid")
		
		while true do
			local headToNPC = (NPC:WaitForChild("HumanoidRootPart").Position - Head.Position).Unit
			local headLook = Head.CFrame.LookVector
			
			local dotProduct = headToNPC:Dot(headLook)
			if dotProduct >= sightLimit then -- checks if the player is looking at the NPC within the sight limit
				Humanoid:TakeDamage(20)
			end
			task.wait()
		end
	end)
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.