You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The Vector3d struct represents a direction and magnitude in 3D space. It is a fundamental geometry class in the AutoCAD .NET API, used extensively for directional calculations, transformations, normal vectors, and geometric operations.
Namespace
Autodesk.AutoCAD.Geometry
Key Properties
Property
Type
Description
X
double
Gets the X component
Y
double
Gets the Y component
Z
double
Gets the Z component
Length
double
Gets the length (magnitude) of the vector
LengthSqrd
double
Gets the squared length (faster than Length)
XAxis
Vector3d (static)
Gets the unit vector (1, 0, 0)
YAxis
Vector3d (static)
Gets the unit vector (0, 1, 0)
ZAxis
Vector3d (static)
Gets the unit vector (0, 0, 1)
Key Methods
Method
Return Type
Description
GetNormal()
Vector3d
Returns normalized unit vector
DotProduct(Vector3d)
double
Calculates dot product with another vector
CrossProduct(Vector3d)
Vector3d
Calculates cross product (perpendicular vector)
GetAngleTo(Vector3d)
double
Gets angle to another vector (radians)
GetAngleTo(Vector3d, Vector3d)
double
Gets signed angle around reference vector
TransformBy(Matrix3d)
Vector3d
Transforms vector by matrix
RotateBy(double, Vector3d)
Vector3d
Rotates vector around axis
Negate()
Vector3d
Returns negated vector
MultiplyBy(double)
Vector3d
Scales vector by scalar
IsParallelTo(Vector3d)
bool
Checks if parallel to another vector
IsPerpendicularTo(Vector3d)
bool
Checks if perpendicular to another vector
IsCodirectionalTo(Vector3d)
bool
Checks if pointing in same direction
IsEqualTo(Vector3d)
bool
Checks equality with default tolerance
IsEqualTo(Vector3d, Tolerance)
bool
Checks equality with custom tolerance
Operator Overloads
Operator
Description
+
Vector addition
-
Vector subtraction
*
Scalar multiplication
/
Scalar division
==
Equality comparison
!=
Inequality comparison
Code Examples
Example 1: Creating and Normalizing Vectors
// Create vectorsVector3dvec1=newVector3d(3,4,0);Vector3dvec2=newVector3d(10,0,0);// Get vector propertiesdoublelength=vec1.Length;// 5.0doublelengthSqrd=vec1.LengthSqrd;// 25.0 (faster calculation)// Normalize to unit vectorVector3dunitVec=vec1.GetNormal();// (0.6, 0.8, 0)// Use predefined axis vectorsVector3dxAxis=Vector3d.XAxis;// (1, 0, 0)Vector3dyAxis=Vector3d.YAxis;// (0, 1, 0)Vector3dzAxis=Vector3d.ZAxis;// (0, 0, 1)ed.WriteMessage($"\nVector: ({vec1.X}, {vec1.Y}, {vec1.Z})");ed.WriteMessage($"\nLength: {length:F2}");ed.WriteMessage($"\nUnit vector: ({unitVec.X:F2}, {unitVec.Y:F2}, {unitVec.Z:F2})");
Vector3dv1=newVector3d(1,0,0);Vector3dv2=newVector3d(0,1,0);// Dot product (scalar result)doubledot=v1.DotProduct(v2);// 0 (perpendicular vectors)// Cross product (vector result - perpendicular to both)Vector3dcross=v1.CrossProduct(v2);// (0, 0, 1) - Z axis// Practical example: check if vectors are perpendicularVector3da=newVector3d(3,4,0);Vector3db=newVector3d(-4,3,0);doubledotAB=a.DotProduct(b);// 0 (perpendicular)ed.WriteMessage($"\nDot product: {dot}");ed.WriteMessage($"\nCross product: ({cross.X}, {cross.Y}, {cross.Z})");ed.WriteMessage($"\nVectors perpendicular: {Math.Abs(dotAB)<0.001}");
Example 4: Angle Calculations
Vector3dv1=newVector3d(1,0,0);// X axisVector3dv2=newVector3d(1,1,0);// 45° from X axis// Get angle between vectors (always positive, 0 to π)doubleangle=v1.GetAngleTo(v2);doubledegrees=angle*(180.0/Math.PI);// Convert to degrees// Get signed angle (with reference vector)Vector3drefVec=Vector3d.ZAxis;doublesignedAngle=v1.GetAngleTo(v2,refVec);ed.WriteMessage($"\nAngle: {angle:F4} radians ({degrees:F2}°)");ed.WriteMessage($"\nSigned angle: {signedAngle:F4} radians");// Practical example: find angle between two linesPoint3dp1=newPoint3d(0,0,0);Point3dp2=newPoint3d(10,0,0);Point3dp3=newPoint3d(10,10,0);Vector3dline1=p1.GetVectorTo(p2);Vector3dline2=p2.GetVectorTo(p3);doublelineAngle=line1.GetAngleTo(line2);ed.WriteMessage($"\nAngle between lines: {lineAngle*(180.0/Math.PI):F2}°");
Example 5: Vector Transformations
Vector3dvec=newVector3d(1,0,0);// Rotate vector 90° around Z axisdoubleangle=Math.PI/2;Vector3drotated=vec.RotateBy(angle,Vector3d.ZAxis);// Result: (0, 1, 0)// Transform by matrixMatrix3drotation=Matrix3d.Rotation(Math.PI/4,Vector3d.ZAxis,Point3d.Origin);Vector3dtransformed=vec.TransformBy(rotation);// Scale vectorVector3dscaled=vec.MultiplyBy(5.0);// (5, 0, 0)ed.WriteMessage($"\nOriginal: {vec}");ed.WriteMessage($"\nRotated 90°: ({rotated.X:F2}, {rotated.Y:F2}, {rotated.Z:F2})");ed.WriteMessage($"\nTransformed: ({transformed.X:F2}, {transformed.Y:F2}, {transformed.Z:F2})");
Example 6: Perpendicular Vector Generation
Vector3dvec=newVector3d(1,1,0);// Get perpendicular vector using cross productVector3dperp1=vec.CrossProduct(Vector3d.ZAxis);perp1=perp1.GetNormal();// Normalize// Alternative: rotate 90°Vector3dperp2=vec.RotateBy(Math.PI/2,Vector3d.ZAxis);perp2=perp2.GetNormal();// Verify perpendicularitydoubledot=vec.DotProduct(perp1);boolisPerpendicular=Math.Abs(dot)<0.001;ed.WriteMessage($"\nOriginal vector: {vec}");ed.WriteMessage($"\nPerpendicular vector: {perp1}");ed.WriteMessage($"\nDot product (should be ~0): {dot:F6}");ed.WriteMessage($"\nIs perpendicular: {isPerpendicular}");
Example 7: Vector Projection
// Project vector A onto vector BVector3dvecA=newVector3d(5,3,0);Vector3dvecB=newVector3d(1,0,0);// X axis// Projection formula: proj_B(A) = (A · B / |B|²) * BdoubledotProduct=vecA.DotProduct(vecB);doublelengthSqrd=vecB.LengthSqrd;Vector3dprojection=vecB*(dotProduct/lengthSqrd);// Get perpendicular component (rejection)Vector3drejection=vecA-projection;ed.WriteMessage($"\nVector A: {vecA}");ed.WriteMessage($"\nVector B: {vecB}");ed.WriteMessage($"\nProjection of A onto B: {projection}");ed.WriteMessage($"\nRejection (perpendicular): {rejection}");// Verify: projection + rejection = originalVector3dsum=projection+rejection;ed.WriteMessage($"\nVerification (should equal A): {sum}");
Example 8: Checking Vector Relationships
Vector3dv1=newVector3d(1,0,0);Vector3dv2=newVector3d(2,0,0);// Parallel to v1Vector3dv3=newVector3d(0,1,0);// Perpendicular to v1Vector3dv4=newVector3d(-1,0,0);// Opposite to v1// Check parallelboolisParallel=v1.IsParallelTo(v2);// true// Check perpendicularboolisPerpendicular=v1.IsPerpendicularTo(v3);// true// Check codirectional (same direction)boolisCodirectional=v1.IsCodirectionalTo(v2);// trueboolisCodirectional2=v1.IsCodirectionalTo(v4);// false (opposite)// Check equality with toleranceTolerancetol=newTolerance(0.001,0.001);Vector3dv5=newVector3d(1.0001,0,0);boolisEqual=v1.IsEqualTo(v5,tol);// trueed.WriteMessage($"\nv1 parallel to v2: {isParallel}");ed.WriteMessage($"\nv1 perpendicular to v3: {isPerpendicular}");ed.WriteMessage($"\nv1 codirectional to v2: {isCodirectional}");ed.WriteMessage($"\nv1 codirectional to v4: {isCodirectional2}");
Example 9: Finding Nearest Entity from a Coordinate
[CommandMethod("FINDNEAREST")]publicvoidFindNearestEntity(){Documentdoc=Application.DocumentManager.MdiActiveDocument;Databasedb=doc.Database;Editored=doc.Editor;// Prompt for pointPromptPointResultppr=ed.GetPoint("\nSelect search point: ");if(ppr.Status!=PromptStatus.OK)return;Point3dsearchPoint=ppr.Value;using(Transactiontr=db.TransactionManager.StartTransaction()){BlockTableRecordbtr=tr.GetObject(db.CurrentSpaceId,OpenMode.ForRead)asBlockTableRecord;EntitynearestEntity=null;doubleminDistance=double.MaxValue;Point3dnearestPoint=Point3d.Origin;foreach(ObjectIdidinbtr){Entityent=tr.GetObject(id,OpenMode.ForRead)asEntity;if(ent==null)continue;// Get closest point on entityPoint3dclosestPt=ent.GetClosestPointTo(searchPoint,false);// Calculate distance using vectorVector3ddistanceVec=searchPoint.GetVectorTo(closestPt);doubledistance=distanceVec.Length;if(distance<minDistance){minDistance=distance;nearestEntity=ent;nearestPoint=closestPt;}}if(nearestEntity!=null){// Calculate direction vectorVector3ddirection=searchPoint.GetVectorTo(nearestPoint);Vector3dunitDirection=direction.GetNormal();ed.WriteMessage($"\n--- Nearest Entity Found ---");ed.WriteMessage($"\nEntity Type: {nearestEntity.GetType().Name}");ed.WriteMessage($"\nDistance: {minDistance:F4}");ed.WriteMessage($"\nNearest Point: ({nearestPoint.X:F2}, {nearestPoint.Y:F2}, {nearestPoint.Z:F2})");ed.WriteMessage($"\nDirection Vector: ({direction.X:F2}, {direction.Y:F2}, {direction.Z:F2})");ed.WriteMessage($"\nUnit Direction: ({unitDirection.X:F4}, {unitDirection.Y:F4}, {unitDirection.Z:F4})");// Highlight the entitynearestEntity.Highlight();// Draw a line from search point to nearest pointLineindicator=newLine(searchPoint,nearestPoint);indicator.ColorIndex=1;// RedBlockTableRecordspace=tr.GetObject(db.CurrentSpaceId,OpenMode.ForWrite)asBlockTableRecord;space.AppendEntity(indicator);tr.AddNewlyCreatedDBObject(indicator,true);}else{ed.WriteMessage("\nNo entities found in current space.");}tr.Commit();}}
Example 10: Creating Offset Lines Using Vectors
// Create offset line perpendicular to originalPoint3dstart=newPoint3d(0,0,0);Point3dend=newPoint3d(10,0,0);doubleoffsetDistance=5.0;// Get line direction vectorVector3dlineDirection=start.GetVectorTo(end);// Get perpendicular vector (rotate 90° around Z)Vector3dperpendicular=lineDirection.RotateBy(Math.PI/2,Vector3d.ZAxis);Vector3doffsetVector=perpendicular.GetNormal()*offsetDistance;// Create offset pointsPoint3doffsetStart=start.Add(offsetVector);Point3doffsetEnd=end.Add(offsetVector);using(Transactiontr=db.TransactionManager.StartTransaction()){BlockTableRecordbtr=tr.GetObject(db.CurrentSpaceId,OpenMode.ForWrite)asBlockTableRecord;// Original lineLineoriginalLine=newLine(start,end);originalLine.ColorIndex=7;// Whitebtr.AppendEntity(originalLine);tr.AddNewlyCreatedDBObject(originalLine,true);// Offset lineLineoffsetLine=newLine(offsetStart,offsetEnd);offsetLine.ColorIndex=3;// Greenbtr.AppendEntity(offsetLine);tr.AddNewlyCreatedDBObject(offsetLine,true);tr.Commit();}ed.WriteMessage($"\nOriginal line: {start} to {end}");ed.WriteMessage($"\nOffset line: {offsetStart} to {offsetEnd}");ed.WriteMessage($"\nOffset vector: {offsetVector}");
// Three points define a planePoint3dp1=newPoint3d(0,0,0);Point3dp2=newPoint3d(10,0,0);Point3dp3=newPoint3d(0,10,0);Vector3dv1=p1.GetVectorTo(p2);Vector3dv2=p1.GetVectorTo(p3);// Normal is perpendicular to both vectorsVector3dnormal=v1.CrossProduct(v2).GetNormal();
Checking if Point is Left or Right of Line
Point3dlineStart=newPoint3d(0,0,0);Point3dlineEnd=newPoint3d(10,0,0);Point3dtestPoint=newPoint3d(5,5,0);Vector3dlineVec=lineStart.GetVectorTo(lineEnd);Vector3dpointVec=lineStart.GetVectorTo(testPoint);// Cross product Z component determines sideVector3dcross=lineVec.CrossProduct(pointVec);if(cross.Z>0)ed.WriteMessage("\nPoint is on the left");elseif(cross.Z<0)ed.WriteMessage("\nPoint is on the right");elseed.WriteMessage("\nPoint is on the line");
Best Practices
Normalization: Always normalize vectors when you need direction only: vec.GetNormal()
Performance: Use LengthSqrd instead of Length when comparing distances
Immutability: Vector3d is a struct; operations return new vectors
Tolerance: Use tolerance-based comparisons for floating-point vectors
Zero Vectors: Check for zero-length vectors before normalizing
Cross Product: Remember that cross product order matters: A × B ≠ B × A
Dot Product: Use for angle calculations and projections
Unit Vectors: Use predefined XAxis, YAxis, ZAxis for clarity