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

Blender脚本问题:无法将粒子位置写入文本文件

问题分析与修复

你的代码能创建文件但无法写入,核心是语法错误导致脚本提前终止,再加上几个逻辑细节问题,以下是分步修复与优化:

1. 修复语法与未定义变量

  • Python循环语句末尾必须加冒号:,你的for i in range(totalFrames)后面缺失冒号,这会直接触发语法错误,导致脚本中断在文件创建步骤,根本没执行写入逻辑。
  • totalFrames变量未定义,需要先获取动画的实际帧范围:
    scene = bpy.context.scene
    totalFrames = scene.frame_end - scene.frame_start + 1
    

2. 粒子坐标的关键坑:局部空间 vs 世界空间

particle.location返回的是粒子在发射物体局部坐标系下的坐标,如果要判断是否经过世界原点,必须转换成世界坐标:

world_loc = bpy.data.objects['Cube'].matrix_world @ particle.location
locX = world_loc.x
locY = world_loc.y

3. 优化文件写入的可读性与安全性

  • 原代码写入的内容无分隔符,后续统计时无法拆分数据,建议用逗号分隔+换行的格式,方便后续用表格工具或脚本处理。
  • 用with语句自动管理文件,避免因忘记关闭文件或异常导致数据丢失。

修正后的完整代码

import bpy

# 获取动画帧范围
scene = bpy.context.scene
start_frame = scene.frame_start
end_frame = scene.frame_end
totalFrames = end_frame - start_frame + 1

# 用with语句自动管理文件生命周期
filepath = 'C:/SomeDirectory/textfile.txt'
with open(filepath, 'w') as file:
    # 绑定粒子系统
    cube_obj = bpy.data.objects['Cube']
    chosenParticles = cube_obj.particle_systems['part'].particles
    
    # 遍历每帧
    for frame in range(start_frame, end_frame + 1):
        scene.frame_set(frame)
        # 遍历每个粒子
        for particle_idx, particle in enumerate(chosenParticles):
            # 转换为世界坐标
            world_loc = cube_obj.matrix_world @ particle.location
            locX = world_loc.x
            locY = world_loc.y
            # 写入带分隔符的结构化数据
            file.write(f"{particle_idx},{locX:.6f},{locY:.6f},{frame}\n")

更高效的替代方案:直接在脚本中统计次数

不用写入文件再二次处理,直接在遍历过程中判断粒子是否经过原点(设置阈值避免浮点精度问题):

import bpy

scene = bpy.context.scene
start_frame = scene.frame_start
end_frame = scene.frame_end
cube_obj = bpy.data.objects['Cube']
chosenParticles = cube_obj.particle_systems['part'].particles
# 原点判定阈值:坐标绝对值小于该值视为经过原点
origin_threshold = 0.01
# 初始化粒子计数字典
particle_origin_count = {p.index: 0 for p in chosenParticles}

# 遍历帧与粒子
for frame in range(start_frame, end_frame + 1):
    scene.frame_set(frame)
    for particle in chosenParticles:
        world_loc = cube_obj.matrix_world @ particle.location
        if abs(world_loc.x) < origin_threshold and abs(world_loc.y) < origin_threshold:
            particle_origin_count[particle.index] += 1

# 输出统计结果
print("粒子经过原点次数统计:")
for idx, count in particle_origin_count.items():
    print(f"粒子{idx}:{count}次")

# 可选:将统计结果写入文件
with open('C:/SomeDirectory/origin_count.txt', 'w') as f:
    f.write("粒子索引,经过原点次数\n")
    for idx, count in particle_origin_count.items():
        f.write(f"{idx},{count}\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:25:21