How would I get the distance between 2 points and would set that as a speed value for a tween?

Hello! I’m trying to tween a part between 2 distances but the speed will be rather to fast or to slow if the distances are different, so I need to get the distance between both of them and set how long that would be and set that for a speed value, anyone know how that would be possible? Thanks!

Use the Pythagorean Theorem, or in simple terms: Vector.Magnitude

local difference = (p0 - p1) -- The Difference between each other (or their offset)
local distance = difference.Magnitude -- the distance between them

-- Math Explanation:
-- The Pythagorean Theorem is used to find the distance between 2 points
-- either being in a 2D space, or a 3D space, with slight modifications
-- to be more simple, we'll go with a 2D example

-- In 2D, the equation for the Pythagorean Theorem is: a² + b² = c²
-- Our Goal here to find what C is equal to, which by the equation
-- you can tell its a times a, plus b times b, but the answer is c²
-- not c itself, so we then need to find the square root of c², which
-- will give us our answer

-- Here is a Simple Example
local p0 = Vector2.new(3, 5) -- X = 3 | Y = 5
local p1 = Vector2.new(6, 10) -- X = 6 | Y = 10

-- These are our two points
-- now our job is to find the difference between them by subtracting them
-- the positions of these points are relative to the origin (0, 0), in order
-- or them to be relative to each other, we need to subtract them, or in other
-- words, Convert the Position to Object Space.

local p = (p0 - p1)
-- after this, we then have to add the axis together, but before we do so,
-- we must square them, which means to multiply itself (Ex: 3² = (3 x 3))
-- which would look like this:

local c2 = p.X^2 + p.Y^2

-- we now have c², we then need to find the square root of c² and then we get
-- our answer, in Lua, we use math.sqrt() to find the square root, or we find the
-- number to the power of 1/2

local distance = math.sqrt(c2)
-- and from there we have our answer

-- As for 3D spaces, we are adding d to the mix, so instead of finding c from c²
-- we are finding d from d², with the following equation: a² + b² + c² = d²

-- If you haven't caught on" (a, b, c) are symbols for (x, y, z) in these examples.
2 Likes

Thank you so much! This helps a lot!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.