Modify Object Placement in FreeCAD Python

Modifying an object's placement in FreeCAD using Python involves manipulating its Placement property, which controls both position (translation) and orientation (rotation) in 3D space. By interacting with the FreeCAD.Vector and FreeCAD.Rotation classes, you can translate objects along specific axes, rotate them around specific points, or redefine their spatial coordinates entirely within the FreeCAD Python console or external scripts.

Accessing the Target Object

Before modifying placement, reference the target document and object:

import FreeCAD

doc = FreeCAD.ActiveDocument
obj = doc.getObject("Box")  # Replace "Box" with your object's internal name

Changing Position (Translation)

An object's location is stored in obj.Placement.Base. You can modify individual axes or assign a new FreeCAD.Vector.

Move by setting a new vector:

obj.Placement.Base = FreeCAD.Vector(10.0, 20.0, 5.0)  # X=10, Y=20, Z=5

Offset a single coordinate:

obj.Placement.Base.x += 15.0
obj.Placement.Base.z -= 5.0

Changing Orientation (Rotation)

Rotation can be defined using an axis-and-angle method or Euler angles (yaw, pitch, roll) via the FreeCAD.Rotation class.

Rotate using an axis and angle (Axis, Degrees):

# Rotate 45 degrees around the Z-axis (0, 0, 1)
axis = FreeCAD.Vector(0, 0, 1)
angle = 45.0
obj.Placement.Rotation = FreeCAD.Rotation(axis, angle)

Rotate using Euler angles (Yaw, Pitch, Roll in degrees):

# FreeCAD.Rotation(yaw, pitch, roll)
obj.Placement.Rotation = FreeCAD.Rotation(30.0, 0.0, 45.0)

Setting Position and Rotation Simultaneously

You can define both position and orientation at once by creating a new FreeCAD.Placement object:

pos = FreeCAD.Vector(50, 0, 25)
rot = FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), 90)  # 90 degrees around X-axis

obj.Placement = FreeCAD.Placement(pos, rot)

Rotating Around a Custom Center

By default, an object rotates around its local origin (0, 0, 0). To rotate around a custom center point, provide the center vector as the third argument to FreeCAD.Placement:

pos = FreeCAD.Vector(0, 0, 0)
rot = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 90)
center = FreeCAD.Vector(10, 10, 0)

obj.Placement = FreeCAD.Placement(pos, rot, center)

Applying the Changes

Whenever you modify placement properties via script, refresh the document to render the changes in the 3D view:

doc.recompute()