Multiplayer CFrame

Look at the Closest Player

Now we are going to take the previous script and make it more complicated. This new version will list all the players and make the block look at the closest player.

First we are going to edit the While loop by commenting out two lines and renaming myLook:

Above this While loop, we are going to create the getClosestAvatarPosition(myPart) function. This new while loop will constantly run that function to make the block look at the closest player.

New Function

Press enter below myPart.Anchored = true to make room for the new function.

Type the following:

Now we are going to start creating a table of information:

For each player, it grabs, plName, plPos, and plDis.

  • plName is a string containing the name.
  • plPos is a Vector3.
  • plDis uses .magnitude to measure distance.

With this information constantly updating, we now can measure who is closest.

Let’s go Hunting!

Staying inside the same function, we will now create the part that determines who is closest and end the function:

So what does this mean?

GREEN Section

Hunting is set to row 1 with all of its information (that’s my player). The script then loops through each PlayerPosition.¬† The [3] means its looking for the smallest plDis or the player closest to the part. When it finds one, it then sets Hunting to that player.

BLUE Section

Once it finds the right player, it returns or spits out the plPos [2] of the closest player so the Part now knows where to look.

RED Section

Just in case somethings is false or no players are visible, these scripts just tell the part to look at itself (part.Position). 

The Whole Script

Use this to check that you did it right:

Multiplayer Test

It will open 3 new windows and you can move your players around. If the Part looks at the closest player, you did it right!

Assignment 

Take a screeshot of 3 players like this and upload it below!