Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by 2 years ago

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)
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 ChromeDarkMode 15 — 2y

1 answer

Log in to vote
0
Answered by 2 years ago
Edited 2 years ago

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)
Ad

Answer this question