You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python重写Blender类方法实现厘米级位置控制?

解决方案:封装位置属性实现自动单位转换

你可以通过Python的@property装饰器在自定义类中封装位置属性,实现输入厘米值自动转换为Blender的米单位(除以100),同时读取时也自动转回厘米,保持单位一致性。

具体实现思路

  • 给Sphere类添加自定义的location属性,替代直接访问obj.location
  • 利用@property的getter方法,将Blender返回的米单位数值乘以100,以厘米形式返回
  • 利用@location.setter方法,接收厘米数值后除以100,再赋值给obj.location

修改后的完整代码

import bpy
from dataclasses import dataclass
import bmesh
from mathutils import Vector


@dataclass
class Sphere():
    def __post_init__(self):
        bm = bmesh.new()
        bmesh.ops.create_uvsphere(bm, u_segments=62, v_segments=36, radius=1)

        mesh = bpy.data.meshes.new('Sphere')
        bm.to_mesh(mesh)
        mesh.update()
        bm.free()
        self.obj = bpy.data.objects.new("Sphere", mesh)
        bpy.context.scene.collection.objects.link(self.obj)
        
    @property
    def location(self):
        # 读取时将米转换为厘米,返回Vector类型保持操作便利性
        return self.obj.location * 100
    
    @location.setter
    def location(self, value):
        # 设置时将厘米转换为米,兼容元组、列表、Vector三种输入形式
        self.obj.location = Vector(value) / 100


s = Sphere()

# 现在直接输入厘米值,会自动转换为米设置给Blender
s.location = (1, 0, 0)  # 对应Blender中的0.01米(1厘米)

# 读取位置时返回的也是厘米单位的Vector对象
print(s.location)  # 输出 <Vector (1.0000, 0.0000, 0.0000)>

额外说明

  • 代码兼容了元组、列表和Blender原生Vector类型的输入,既保留了手动输入坐标的简洁性,也支持Vector对象的链式操作
  • 如果不需要Vector类型,也可以将getter的返回值改为元组,适配纯数值场景

内容的提问来源于stack exchange,提问作者nammerkage

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 00:45:24