I am trying to figure out a very simple python command to move the selected object(or move the object by name) to the cursor location. Anyone know the command to do this?
Thank you!
Cursor location is global
The location of the cursor can be considered as "global coordinates". The cursor has no parent. When the cursor location is set to zero, it sits at the scene origin.
An object's location
is relative to its parent. Its "global" or "world" transforms can be gleaned from obj.matrix_world
.
To get an object in the scene by name
name = "Foo"
scene = context.scene
obj = scene.objects.get(name)
If there is no object named "Foo" obj is None
To move the object to the cursor location.
obj.matrix_world.translation = scene.cursor.location
To align both location and rotation to the cursor (Note assumes obj
has unit scale)
obj.matrix_world = scene.cursor.matrix
I would recommend writing a little function that copies the cursor's location and sets it for the active object.
import bpy
def snap_active_to_cursor(obj: bpy.types.Object, copy_rotation=False):
cursor = bpy.context.scene.cursor
active_object = bpy.context.view_layer.objects.active
active_object.location = cursor.location
if copy_rotation:
active_object.rotation_euler = cursor.rotation_euler
obj = bpy.context.scene.objects["Cube"]
snap_active_to_cursor(obj)
If you want to move all selected objects individually your function could look like this:
def snap_selected_to_cursor(copy_rotation=False):
cursor = bpy.context.scene.cursor
for obj in bpy.context.view_layer.objects.selected:
obj.location = cursor.location
if copy_rotation:
obj.rotation_euler = cursor.rotation_euler
Blender already has an operator with similar functionality, however it requires the 3D View as context. Since custom contexts are not worth the hassle for as simple task like this, I wouldn't use bpy.ops.view3d.snap_selected_to_cursor(use_offset=True)
within scripts/add-ons when you only want to move the active object.