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

How to make an NPC face a player?

Asked by
RedCombee 585 Moderation Voter
9 years ago

I'm thinking of how I will go about making a script that lets you talk to an NPC in a certain range that also makes the NPC face you when you initiate the conversation.

2 answers

Log in to vote
3
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
9 years ago

This is actually simple to do.

To find the distance between you and the NPC we much subtract your torso's position from the NPC torso's position. This will give you the difference between the points.

For example, if PartA's y is 9, and PartB's y is 4, if we do

print(PartA.Position.y - PartB.Position.y)

the output will show 5. If you measure the parts manually, you will see that they are five studs apart on the y axis (five studs apart from their centers, not their edges). Therefore subtracting positions gives you the space between them.

However, subtracting Vector3's still gives you three numbers. That's why we use magnitude. The official definition from the wiki is, Magnitude is a term used across mathematics that means several things. In vector theory, the magnitude of a vector is the length of a vector. Which is confusing. Basically, magnitude converts the three numbers we got earlier into a single number equal to the distance between the center of the parts. Although probably not technically correct, this is how it seems to work.

print((PartA.Position - PartB.Position).magnitude)

You can do the same thing to the torsos.

if (character.Torso.Position - NPC.Torso.Position).magnitude <= 10 then
    --do stuff
end

To actually make the NPC look at you is much easier. Just use the CFrame.new(startPosition,lookAt) constructor.

NPC.Torso.CFrame = CFrame.new(NPC.Torso.Position,character.Torso.Position) --Make the NPC stay in the same spot but rotate to the player. 
0
Sorry to say but I only needed the last snippet of code. I already know how to use magnitude. RedCombee 585 — 9y
0
magnitude = the suare root of (x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2 RedCombee 585 — 9y
0
Uh... Yeah. Math is bad for my soul. Perci1 4988 — 9y
Ad
Log in to vote
-3
Answered by
Vathriel 510 Moderation Voter
9 years ago

Well, this is actually quite interesting because there are several ways to do that, actually CFraming the NPC would be harder, but if it's unanchored with a humanoid you can find the midpoint between the character and the NPC and have the npc walk to that point using the .MoveTo method. X2+X1/2 and Z2+Z1/2, you can set the Y value to whatever you want because it really shouldn't matter, unless you're running the path finding program as well, or having it jump or something.

Answer this question