Cleanup
- You should really use better variable names.
Child
is a poor name for a Gate
.
Object
is a poor name for a Player
.
GetDistance
is a poor name for something that doesn't return a number. IsNearGate
or NearGate
makes more sense.
- You don't need parenthesis around conditions, and it's not idiomatic to include them.
- It's widely regarded best to fail fast. There's no reason for
GetDistance
/NearGate
to only continue if it's given a player. The only check that might belong is assert(Player:IsA("Player"))
. It is the caller's responsibility to give the right parameters.
The Problem
There are two problems with this code.
First, that only the first torso will be tracked by this script -- if they die, you'll still have Torso
pointing to the first torso they had. This actually won't matter, because of the second point:
.Changed
doesn't fire for changes caused by physics. Consequently, while teleporting the player will trigger the changed event, walking won't.
There isn't really a good event to get when the player moves (it would happen too often anyway). It's much more straightforward to just check every half a second with a while
loop:
1 | Players.PlayerAdded:connect( function (Player) |
3 | if NearGate(Player) then |
4 | print (Player.Name .. " is close to a gate" ) |
Note that DistanceFromCharacter returns 0 if the player doesn't have a head, so between lives this will believe that they are near the gate. It might be a good idea to require Distance
to also be above, say, .01
in addition to being less than RequiredDistance