Blender API技术求助:如何让选中对象绕自身中心X轴旋转
解决Blender对象绕自身中心X轴旋转的问题
问题原因
你遇到的问题有两个核心原因:
- 原代码中旋转操作
bpy.ops.transform.rotate写在循环外部,仅会对最后一个激活的对象生效,其他符合条件的对象不会被旋转。 - 默认的
bpy.ops.transform.rotate依赖上下文设置,可能使用了全局坐标系或3D游标作为旋转中心,导致对象绕角落而非自身中心旋转。
解决方案
推荐两种可靠的实现方式,优先选择第一种(非ops方法),因为它不依赖上下文,批量处理更稳定:
方法1:直接修改对象旋转属性(推荐)
通过修改对象的rotation_euler属性,直接绕自身原点旋转。如果对象原点已在几何中心,这就是绕中心旋转;若原点不在中心,可先调整原点位置。
import bpy import math # 旋转角度(90度转弧度) rotate_angle = math.radians(90) for obj in bpy.data.objects: if obj.location.x > 1.1: # 若需先将对象原点移到几何中心,取消下方注释 # bpy.context.view_layer.objects.active = obj # obj.select_set(True) # bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS') # obj.select_set(False) # 绕自身X轴旋转 obj.rotation_euler.x += rotate_angle print(f"已旋转对象: {obj.name}, 位置X: {obj.location.x}") print("hello33")
方法2:修正bpy.ops.transform.rotate的上下文参数
明确指定使用对象自身坐标系和旋转中心(几何中心或对象原点),确保旋转行为符合预期:
import bpy import math from mathutils import Vector # 计算对象几何中心的函数 def get_geo_center(obj): local_center = 0.125 * sum((Vector(b) for b in obj.bound_box), Vector()) return obj.matrix_world @ local_center rotate_angle = math.radians(90) for obj in bpy.data.objects: if obj.location.x > 1.1: obj.select_set(True) bpy.context.view_layer.objects.active = obj # 绕自身几何中心的X轴旋转 bpy.ops.transform.rotate( value=rotate_angle, orient_axis='X', orient_type='LOCAL', # 使用对象自身坐标系 center_override=get_geo_center(obj) # 指定几何中心为旋转中心 ) print(obj.location.x) print("hello33")
关键注意事项
- 避免在批量处理中过度依赖
bpy.ops系列函数,这类函数受当前选中状态、激活对象等上下文影响,稳定性不如直接操作对象属性。 - 若对象原点与几何中心不重合,必须先调整原点位置,或在旋转时指定几何中心作为旋转基准点。
内容的提问来源于stack exchange,提问作者ffejrekaburb
相关产品推荐
相关产品推荐

