Blender导出器的Python脚本

1 投票
1 回答
1869 浏览
提问于 2025-04-17 10:00

我正在尝试写一个非常简单的脚本,把一些基本的形状导出到Blender里。我需要绘制圆柱体,放在不同的角度和位置上。我有关于位置偏移和尺寸的信息。

import bpy
import bgl
from mathutils import *
from math import *

material = bpy.data.materials.new('red')
material.diffuse_color = (1.0,0.0,0.0)


def draw_cylinder(name,material,radius,depth,location,rotation,offsetPosition,offsetAngle):

    bgl.glRotatef(*offsetAngle[:4]) 
    bgl.glTranslatef(*offsetPosition[:3])

    bpy.ops.mesh.primitive_cylinder_add(radius=radius, depth=depth, location=location, rotation=rotation)

    Cylinder = bpy.context.active_object
    Cylinder.name = name
    Cylinder.active_material = material

    bgl.glTranslatef(*[i*-1 for i in offsetPosition[:3]])
    bgl.glRotatef(*[i*-1 for i in offsetAngle[:4]])

    return Cylinder

cmpt = draw_cylinder('first',material,radius=1,depth=2,location=(-1,0,0),rotation=(pi/2,0,0),offsetPosition=(10,2,7),offsetAngle=(pi/2,0,1,0))

但是,这段代码并没有把圆柱体画在(9,2,7)这个位置,也没有沿着y轴旋转。我哪里出错了呢?我该怎么修正这个问题呢?非常感谢你的帮助。

补充说明:我使用的是Blender 2.60版本(Python交互控制台3.2.2)。输出显示圆柱体在(-1,0,0)的位置。我希望它能在(9,2,7)这个位置(位置+偏移位置)。

1 个回答

1

在函数 draw_cylinder 中,你需要把两个向量加起来:

pos = (
    location[0]+offsetPosition[0],
    location[1]+offsetPosition[2],
    location[1]+offsetPosition[2],
)

然后

bpy.ops.mesh.primitive_cylinder_add(radius=radius, depth=depth, location=pos, rotation=rotation)

[编辑] 如果你需要更复杂的操作,可以看看 mathutils 库

撰写回答