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

What is the problem with this?

Asked by 9 years ago
game.Players.PlayerAdded:connect(function(player)
    local character = player.Character
    if character.Head.Position.Z <= -100 then
        game.ServerStorage.t2:Clone().Parent = game.Workspace
    elseif character.Head.Position.Z > 100 then
        game.Workspace.t2:Destroy()
    end
end)

I am trying to make an event happen when a character's Z position is <= -100.

I'm trying to make this work. I'm assuming it's because this script only fires when a player joins, but I cannot think of another way to make this work. Any suggestions?

1 answer

Log in to vote
0
Answered by 9 years ago

First, use the character added event to see if the head EXISTS.

game.Players.PlayerAdded:connect(function(player)
    player.CharacterAdded:connect(function(character)
    if character.Head.Position.Z <= -100 then
        game.ServerStorage.t2:Clone().Parent = game.Workspace
    elseif character.Head.Position.Z > 100 then
        game.Workspace.t2:Destroy()
    end
end)
end)

What you can also use is the :DistanceFromCharacter() function. Instead of seeing if the z is -100 studs away.

--LocalScript
local player = game:GetService("Players").LocalPlayer

player:GetDistanceFromCharacter(0,0,0)--If the character steps backwards a stud it would return 1.

So with that we can make your script better.

game.Players.PlayerAdded:connect(function(player)
    player.CharacterAdded:connect(function(character)
local dist = player:DistanceFromCharacter(0,0,0)
    if dist < 100 then
        game.ServerStorage.t2:Clone().Parent = game.Workspace
    elseif dist > 100 then
        game.Workspace.t2:Destroy()
    end
end)
end)

But this only works once. After the character respawns. We can use a loop to get around them.

game.Players.PlayerAdded:connect(function(player)
    player.CharacterAdded:connect(function(character)
        local dist = player:DistanceFromCharacter(0,0,0)
        while wait() do --May lag.
            if dist < 100 then
                   game.ServerStorage.t2:Clone().Parent = game.Workspace
            elseif dist > 100 then
                   game.Workspace.t2:Destroy()
        end
    end
end)
end)


Hope this helps!

Ad

Answer this question