part_position = game.Workspace.Eye.Position player = game.Players.LocalPlayer Character = player.Character Torso = Character.Torso Position = Torso.Position function getMagnitude(X,Y,Z) return math.sqrt((X^2)+(Y^2)+(Z^2)) end while getMagnitude(part_position.X,part_position.Y,part_position.Z) - getMagnitude(Position.X,Position.Y,Position.Z) < 5 do print(getMagnitude(part_position.X,part_position.Y,part_position.Z) - getMagnitude(Position.X,Position.Y,Position.Z)) wait(1) end
Here is what I tried to do. This is a local script inside a brick. I want it to print the magnitude of the distance between the player and the object if the player gets too close.
You shouldn't be defining getMagnitude
yourself. ROBLOX has it built in. (In general, you should pretty much never need to use .x
, .y
and .z
on a vector)
part_position.magnitude
You only ever set (ie., change) the Position
and part_position
variable at the beginning of the script.
That means if the player moves, Position
isn't going to change. You have to explicitly ask for the position of the player each time you need it to be fresh.
Part.Position.magnitude - Torso.Position.magnitude
The difference of magnitudes is not the way to measure the distance between things. (That clearly doesn't make sense. Magnitudes are numbers; a difference could be negative -- what is a negative distance? Magnitude of a position is also meaningless, because it makes the origin special).
The magnitude of the difference in position is what you want:
local distance = (Torso.Position - Part.Position).magnitude
You are not using while
in a meaningful way. while
will stop once the condition fails. Thus this will print until the player is not within five studs, and then the script is over.
What you want to do is:
So write that!
while wait(1) do local distance = (Torso.Position - Part.Position).magnitude if distance < 5 then print(distance) end end