How do I find the length between 2 objects

title explains it. also how do I find the spot in between 2 objects

Make a rectangle as wide/long as the space between two objects. Find the width/height of that rectangle.

Oh yes, time for MATH (actually this time it’s just gonna be basic math)

So say you have these two objects


^ I put a red dot in their x and y positions for demonstration purposes

To get the x difference between both shapes, you can just subtract their x values.


You also want to take the absolute value to make sure you don’t get a negative difference between both shapes when you subtract their x values.
Code wise, assuming the shapes are called “triangle” and “circle,” here’s how it’d look like in code.

Math.abs(triangle.x-circle.x)

Same for the y difference.
Now say you don’t want just the x and y difference, you want the actual space between the two shapes. I moved the shapes around for this demonstration.

This here is simple triginometry so I won’t bother explaining much. All you need to know is this formula: Distance = √(∂x ^2 + ∂y ^2)
Practically the pythagorean theorem rewritten.

To explain:
∂x = delta x = difference in x = absolute value of triangle x minus circle x = Math.abs(triangle.x-circle.x)
∂y = delta y = difference in y = absolute value of triangle y minus circle y = Math.abs(triangle.y-circle.y)


Code:

difference = Math.sqrt(Math.abs(triangle.x-circle.x)**2 + Math.abs(triangle.y-circle.y)**2)

To find the spot between the two objects, just take the difference x and divide it by 2 to find half the length, then add that to the x value of another shape to get the middle point.
Same for y values.

midX = (triangle.x-circle.x)/2 + circle.x;
midY = (triangle.y-circle.y)/2 + circle.y;
1 Like

thanks this is super helpful

1 Like