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

I'm trying to make a part look the nearest player, but it doesn't rotate any. A little help?

Asked by 5 years ago

If you need the script

local Lord = game.Workspace:WaitForChild("Lord")

local Player = game:GetService("Players").LocalPlayer
local Character = game.Workspace:WaitForChild(Player.Name)
local PlayerHead     = Character:WaitForChild("Lord")

while true do
    wait()


    Lord.CFrame = CFrame.new(Lord.CFrame.p,PlayerHead.CFrame.p)

end

I'm not sure what's wrong but I need to fix it. Just so you know, "Lord" is the part.

1 answer

Log in to vote
0
Answered by
royaltoe 5144 Moderation Voter Community Moderator
5 years ago

Your current code only checks the character's position at the beginning of the game. I provided some code for you that works. You need to put it in the while loop for it to check every couple milliseconds. Still, you are not checking for the closest player, you are only having the script look at the local player.

getClosestPlayer() gets the closest player by checking their distance from the part. with that information, we can use CFrame.new() to change the part's position.

CFrame.new() has to parameters, the first parameter being the position you want the part to be at, and the second parameter being a position you want the part to look at.

CFrame.new(position, lookAt) 

since we got the closest player with getClosestPlayer(), we can make the part's 'lookAt' parameter be the player's humanoidRootPart. which means the part looks at the closest player.

part = script.Parent

function getClosestPlayer()
    local closestPlayer = nil
    local closestMagnitude = math.huge

    for _, player in pairs(game:GetService("Players"):GetPlayers())do
        if(player.Character)then 
            local magnitude = (player.Character.HumanoidRootPart.Position - part.Position).magnitude 
            if(magnitude < closestMagnitude)then
                closestPlayer = player
            end
        end 
    end

    return closestPlayer
end 

while(wait())do

    local closestPlayer = getClosestPlayer()

    if(closestPlayer)then
        part.CFrame = CFrame.new(part.Position, closestPlayer.Character.HumanoidRootPart.Position)
    end
end
0
Thank you, that helped me so much! DerpyTsumTsum 2 — 5y
Ad

Answer this question