Compute Distance Between Objects

The attached FRED file contains an embedded script which shows how you can calculate the distance between two objects using the scripting language. The script works by using the TransformPosition command, which takes a starting coordinate system, a new coordinate system and a position vector defined by its x, y, and z components. The x, y and z values, input to the TransformPosition command, are modified in place (by reference) to convert the vector from the starting coordinate system to the new coordinate system. In this manner you can transform the vertex location of a surface (as an example) to global coordinates by using the syntax below, where n is the node number of the surface:

x = 0 : y = 0 : z = 0
TransformPosition( n, -1, x, y, z )

To compute the distance between two surfaces, we call this function twice and then compute the length of the vector connecting the two points using GetLength3D:

x1 = 0 : y1 = 0 : z1 = 0
x2 = 0 : y2 = 0 : z2 = 0
TransformPosition( n1, -1, x1, y1, z1 )
TransformPosition( n2, -1, x2, y2, z2 )
GetLength3D( x2-x1, y2-y1, z2-z1, len )
Print “Distance between two surfaces is ” & len

Note that we don’t necessarily have to convert both vertices to global coordinates. We could alternatively convert one vertex into the coordinate system of the other surface and then retrieve the length of the resulting vector. You may have reason to perform the calculation one way or the other.

Although the example file and script are available separately for download below, the content of the full script is provided here:

Option Explicit

n As Long
x As Double
y As Double
z As Double
End Type

Sub Main

Dim p1 As T_POINT, p2 As T_POINT

‘Node number and point on the first object
p1.n = FindFullName( “Geometry.Plane” )
p1.x = 0
p1.y = 0
p1.z = 0

‘Node number and point on the second object
p2.n = FindFullName( “Geometry.Plane 1” )
p2.x = 0
p2.y = 0
p2.z = 0

Print “Distance between objects is ” & CalcDistance(p1, p2) & ” ” & GetUnits()

End Sub

Function CalcDistance( ByVal p1 As Variant, _
ByVal p2 As Variant ) As Double

‘Convert the first point from local to global
TransformPosition(p1.n, -1, p1.x, p1.y, p1.z)

‘Convert the second point from local to global
TransformPosition(p2.n, -1, p2.x, p2.y, p2.z)

‘Compute the length of the vector
Dim dist As Double
GetLength3D(p2.x-p1.x, p2.y-p1.y, p2.z-p1.z, dist)

‘Return the length
Return dist

End Function

Download the FRED script: CalculateDistance.frs

Download the FRED file: ComputeDistanceExample.frd