I want to make a script that plays a walking animation on an NPC, and when a player is near it then it will play a grabbing animation. I sort of have a script but I’m not sure to actually detect if a humanoid is Infront of the NPC and to make the NPC then play the grab animation.
local char = script.Parent
local hum = char:WaitForChild("Humanoid")
local animation = hum:LoadAnimation(script.Animation) --the walk animation
local anim = hum:LoadAnimation(script.Parent.Animation2) --the grab animation
local function walk()
animation:Play() --plays the walk animation
end
local function attack()
anim:Play() --plays the grab animation
end
If youre looking for position, that is simple. Just check (Position1-Position2).Magnitude. This will give you the absolute distance between the two positions.
If youre looking to check if the npc is looking at the player, I would just calculate the dot product. Roblox gives us a function for this - Vector3:Dot() - which would be especially useful in your case, and would save you a lot of manual math.
Dot product is a bit more complicated, as you need to well understand how vector3 works and how the three coordinates work. Specifically with lookvectors. Bascially LookVector1:Dot(LookVector2) will return a number between -1 and 1 denoting the magnitude of the directional difference between the two. It can be visualized a lot better in this article: The Ultimate Guide to Vector3:Cross() and Vector3:Dot()