import bpy
import mathutils
import numpy as np
import subprocess
bpy.ops.wm.open_mainfile(filepath=r"D:\python_code\myCode\13_blender_simulation\sonar3.blend") # 打开blender文
# 设置参数
num_cameras = 256
rows = 16
cols = 16
camera_spacing = 2.0 # 相机之间的间隔
target_location = mathutils.Vector((0, 0, -10)) # 目标位置
# 删除现有相机(可选)
# for obj in bpy.data.objects:
# if obj.type == 'CAMERA':
# bpy.data.objects.remove(obj)
# bpy.data.cameras.remove(obj.data)
scene = bpy.context.scene
# 由于直接在遍历过程中删除对象可能会导致问题,我们可以改用以下方法来安全地删除所有摄像机:
cameras_to_remove = [obj for obj in scene.objects if obj.type == 'CAMERA']
for camera in cameras_to_remove:
#scene.objects.unlink(camera)
bpy.data.objects.remove(camera, do_unlink=True) # 现在可以安全地删除对象和数据了
# 注意:在某些情况下,你可能还需要检查并删除与摄像机相关的任何数据块(如摄像机数据),
# 但在这个简单的例子中,由于我们删除了整个对象,所以这些数据块也会被自动删除。
# 刷新UI以反映更改(通常不是必需的,但在某些情况下可能有助于确保更改立即生效)
#bpy.context.window.update()
# 创建相机集合
camera_list = []
# 创建并放置相机
for i in range(rows):
for j in range(cols):
# 计算相机位置
x = (j - cols // 2) * camera_spacing
y = (i - rows // 2) * camera_spacing
location = mathutils.Vector((x, y, 0))
# 创建相机
camera_data = bpy.data.cameras.new(f"Camera_{i}_{j}")
camera_object = bpy.data.objects.new(f"Camera_{i}_{j}", camera_data)
bpy.context.scene.collection.objects.link(camera_object)
camera_object.location = location
# 设置相机朝向目标
camera_object.rotation_mode = 'QUATERNION'
camera_object.rotation_quaternion = (location - target_location).to_track_quat('-Z', 'Y')
camera_list.append(camera_object)
# 更新所有相机朝向的函数
def update_camera_orientations(target_location):
for camera in camera_list:
camera_location = camera.location
camera.rotation_quaternion = (camera_location - target_location).to_track_quat('-Z', 'Y')
# 测试更新相机朝向
new_target_location = mathutils.Vector((5, 5, -10))
update_camera_orientations(new_target_location)
print("相机创建和朝向设置完成。")
#保存Blender文件
bpy.ops.wm.save_mainfile(filepath=r"D:\python_code\myCode\13_blender_simulation\sonar3.blend")
blender_path = r"D:\Software_Installation\blender\blender.exe"
blend_file_path = r'D:\python_code\myCode\13_blender_simulation\sonar3.blend'
subprocess.run([blender_path, blend_file_path, "-noaudio"], check=True)
python打开、写入、保存blender文件
最新推荐文章于 2025-06-10 20:34:35 发布