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

How to find position between a part and a player?

Asked by 7 years ago
Edited 7 years ago
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.

0
Which position? Use your words! What do you want to accomplish? BlueTaslem 18071 — 7y

1 answer

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago
Edited 7 years ago

1. use magnitude!

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

2. update your variables!

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

3. compute distance correctly!

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

4. use while right!

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:

  • For forever,
    • if the player is close, print.

So write that!

while wait(1) do
    local distance = (Torso.Position - Part.Position).magnitude
    if distance < 5 then
        print(distance)
    end
end
Ad

Answer this question