import cadquery as cq
cone = cq.Solid.makeCone(1, 0, 2)
assy = cq.Assembly()
assy.add(cone, name="cone0", color=cq.Color("green"))
assy.add(cone, name="cone1", color=cq.Color("blue"))
assy.constrain("cone0@faces@<Z", "cone1@faces@<Z", "Axis")
assy.solve()
show_object(assy)
如果 param 参数设置为零,则两个对象将指向同一方向。 这通常在一个物体穿过另一个物体时使用,例如一根钉进入板上的孔:

import cadquery as cq
plate = cq.Workplane().box(10, 10, 1).faces(">Z").workplane().hole(2)
cone = cq.Solid.makeCone(0.8, 0, 4)
assy = cq.Assembly()
assy.add(plate, name="plate", color=cq.Color("green"))
assy.add(cone, name="cone", color=cq.Color("blue"))
# place the center of the flat face of the cone in the center of the upper face of the plate
assy.constrain("plate@faces@>Z", "cone@faces@<Z", "Point")
# set both the flat face of the cone and the upper face of the plate to point in the same direction
assy.constrain("plate@faces@>Z", "cone@faces@<Z", "Axis", param=0)
assy.solve()
show_object(assy)
在创建轴约束时,将根据对象的类型以三种不同方式之一提取方向矢量:
- 面:使用 normalAt()
- Edge 和 geomType() 是“CIRCLE”:使用 normal()
- Edge 和 geomType() 不是“CIRCLE”:使用 tangentAt()
使用任何其他类型的对象都会引发 ValueError。 到目前为止,最常见的用例是从面定义轴约束。

import cadquery as cq
from math import cos, sin, pi
# Create a sinusoidal surface:
surf = cq.Workplane().parametricSurface(
lambda u, v: (u, v, 5 * sin(pi * u / 10) * cos(pi * v / 10)),
N=40,
start=0,
stop=20,
)
# Create a cone with a small, flat tip:
cone = (
cq.Workplane()
.add(cq.Solid.makeCone(1, 0.1, 2))
# tag the tip for easy reference in the constraint:
.faces(">Z")
.tag("tip")
.end()
)
assy = cq.Assembly()
assy.add(surf, name="surf", color=cq.Color("lightgray"))
assy.add(cone, name="cone", color=cq.Color("green"))
# set the Face on the tip of the cone to point in
# the opposite direction of the center of the surface:
assy.constrain("surf", "cone?tip", "Axis")
# to make the example clearer, move the cone to the center of the face:
assy.constrain("surf", "cone?tip", "Point")
assy.solve()
show_object(assy)11、平面约束
平面约束只是 点约束和 轴约束的组合。 它是常用约束组合的便捷快捷方式。 它可用于将前面的示例从两个约束缩短为一个:
assy = cq.Assembly()
assy.add(surf, name="surf", color=cq.Color("lightgray"))
assy.add(cone, name="cone", color=cq.Color("green"))
-# set the Face on the tip of the cone to point in
-# the opposite direction of the center of the surface:
-assy.constrain("surf", "cone?tip", "Axis")
-# to make the example clearer, move the cone to the center of the face:
-assy.constrain("surf", "cone?tip", "Point")
assy.constrain("surf", "cone?tip", "Plane")
assy.solve()
show_object(assy)
此代码的结果与上述两个约束示例相同。
面约束的成本函数,请参见 点约束 和 轴约束 部分。 param 参数应用于 Axis 并且应该保留为“mate”样式约束(两个表面接触)的默认值,或者可以设置为 0 用于通过表面约束(参见 轴约束部分中的描述)。
12、点平面约束点平面约束将第一个对象的中心定位在第二个对象定义的平面内。 成本函数是:

其中:
- c是第一个对象的中心,
- poffset是从第二个对象创建的平面,在平面的法线方向上偏移 param参数,并且
- dist(a,b)是点 a 和 平面 b之间的距离
