✓ Accepted answer
Magnitude
There's a special operation you can preform on each Vector3 value, which is called "magnitude" (or, "Magnitude"). Magnitude can give you the distance between two objects by subtracting their positions, and using this magnitude operation on the result. For example:
local Vector1 = Vector3.new(0,50,45)
local Vector2 = Vector3.new(90,87,-10)
print((Vector1-Vector2).Magnitude)
The code above will display the distance between these two 3D coordinates, which we can utilize in your situation to create a logic gate using an if statement. Here's how we could check the distance:
local Vector1 = Vector3.new(0,50,45)
local Vector2 = Vector3.new(90,87,-10)
local Range = 10
local Distance = (Vector1-Vector2).Magnitude
if Distance > Range then
print("Out of range")
else
print("In range")
end
Similarly with your situation, we'd apply the same logic. I'd suggest studying this solution to your question, to understand the use of magnitude a lot better:
local Player = game:GetService("Players").LocalPlayer
local Character = Player.CharacterAdded:wait()
local Torso = Character:WaitForChild("Torso")
local Mouse = Player:GetMouse()
local TeleportRange = 50
Mouse.KeyDown:connect(function(Key)
if Key:lower() == "f" then
local Distance = (Mouse.Hit.p-Torso.Position).Magnitude
if Distance < TeleportRange then
Torso.CFrame = CFrame.new(Mouse.Hit.p)
else
print("Too far")
end
end
end)
Suggestions
I also suggest studying how UserInputService works, since it's very fun to work with and is the preferred method of detecting user input over the PlayerMouse object: http://wiki.roblox.com/index.php?title=API:Class/UserInputService
And that's about it. Hope this helped, let me know if you have any questions.
1 comment
Thanks for helping! It works like a charm.