# Trying to visual the distance between to spheres

the problem is that it works but only on one side, its kind of confusing for me to explain so heres a video of it

code

``````local earth = workspace.earth
local sun = workspace.sun

local part = Instance.new("Part")
part.Anchored = true
part.BrickColor = BrickColor.new("Bright blue")

game:GetService("RunService").Heartbeat:Connect(function(dt)
local distance = sun.Position - earth.Position

part.Size = Vector3.new(.5,.5,distance.Z)
part.CFrame = CFrame.new(earth.Position + distance / 2, sun.Position)

part.Parent = workspace
end)
``````
``````part.Size = Vector3.new(.5,.5,distance.Z)
``````

Try changing this to:

``````part.Size = Vector3.new(.5, .5, math.abs(distance.Z))
``````

I think your Z-component in your distance vector might end up being negative in some cases. You can’t have a negative part size.

yeah that is true man, thanks but how did you come to this conlcusion though what exactly does math.abs do wait doesnt it change a positive into a positive and a negative to a positive?

That’s right, it takes the ‘absolute value’ of a number. This indeed means that a positive stays positive and a negative gets multiplied by -1.

1 Like

Use Vector.Magnitude instead of the Z component

``````game:GetService("RunService").Heartbeat:Connect(function(dt)
local distance = (sun.Position - earth.Position).Magnitude

part.Size = Vector3.new(.5,.5,distance)
part.CFrame = CFrame.new(earth.Position, sun.Position) * CFrame.new(0, 0, -distance / 2)

part.Parent = workspace
end)
``````
1 Like

Another easy way to get the distance between two objects is like this:

``````local distance = (earth.Position - sun.Position).magnitude
``````
1 Like

Oh alright let me try that real quick

@XandertjeKnal and @rokoblox5 thanks ill try that quick

It worked thanks both of you

If you want the distance to be correct in any axis, not just their distance on the Z axis, use magnitude:

``````local distance = (sun.Position - eart.Position).magnitude
``````

`magnitude` is a property of Vector3 that is the length of a line drawn from the Origin, (0,0,0) to wherever the Vector is (X,Y,Z). It is equivalent to `math.sqrt(vec3.X^2 + vec3.Y^2 + vec3.Z^2)`, which is just the pythagorean theorem.

1 Like

thanks all alot guys I shouldve known to use magnitude, it worked!

For a better explanation of my answer, `Vector.Magnitude` returns the distance of the Vector.
At the `part.CFrame = CFrame.new...` part, I’m placing the part at the earth’s position, looking at the sun’s position then pushing it towards it by half the distance.

I used -distance since -Z = front and +Z = back (Yes it’s inverted.)

1 Like

Yeah i get magnitude its the distance between two vectors

or like the legnth of the vector