求空间直线与平面的交点
代码来自这篇文章:
https://www.jianshu.com/p/4b630c11f9f5
话不多说,
直接上代码:
[CommandMethod("MyGroup", "Test01", "Test01Local", CommandFlags.Modal)] public void MyCommand_Test01() // This method can have any name { Point3d p1 = new Point3d(2, 3, 4); Point3d p2 = new Point3d(3, 4, 5); Vector3d v1 = new Vector3d(1, 2, 3); Vector3d v2 = new Vector3d(2, 3, 4); Line line = new Line(p1, p1 + v1); Circle circle = new Circle(p2, v2, 5); var pt = GetInt(p1, v1, p2, v2); Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage(pt.ToString()); DBPoint dBPoint = new DBPoint(pt); using (Transaction tr = Application.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(Application.DocumentManager.MdiActiveDocument.Database.BlockTableId, OpenMode.ForRead, false); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false); btr.AppendEntity(line); btr.AppendEntity(circle); btr.AppendEntity(dBPoint); tr.AddNewlyCreatedDBObject(line, true); tr.AddNewlyCreatedDBObject(circle, true); tr.AddNewlyCreatedDBObject(dBPoint, true); tr.Commit(); } } /// <summary> /// 求直线与平面的交点 /// https://www.jianshu.com/p/4b630c11f9f5 /// </summary> /// <param name="lP">直线上的一点</param> /// <param name="lD">直线方向</param> /// <param name="pP">平面上一点</param> /// <param name="pD">平面上方向</param> /// <returns交点</returns> static Point3d GetInt(Point3d lP, Vector3d lD, Point3d pP, Vector3d pD) { if (lD.X * pD.X + lD.Y * pD.Y + lD.Z * pD.Z == 0) { //方向向量与平面平行,没有交点,返回原点应该不合适,需要注意 return Point3d.Origin; } double m = ((pP.X - lP.X) * pD.X + (pP.Y - lP.Y) * pD.Y + (pP.Z - lP.Z) * pD.Z) / (pD.X * lD.X + pD.Y * lD.Y + pD.Z * lD.Z); return new Point3d(lP.X + lD.X * m, lP.Y + lD.Y * m, lP.Z + lD.Z * m); }
在AutoCAD中测试结果如下: