2011年10月31日月曜日

Blender:Pythonスクリプト:オブジェクトを連続的に動かす

Text Editorで次のようなプログラムを書いてAlt+Pを何度も押すと少しずつCubeが動きます。

import bpy

bpy.data.objects["Cube"].location += Vector((1.0,0,0))

ところがこれを連続的に動かして、アニメーションのように見ようとして

import bpy
from mathutils import *
import time

print('start******************')

duration = 0.3
time.sleep(duration)

for i in range(10):
    bpy.data.objects["Cube"].location += Vector((1.0,0,0))
    time.sleep(duration)

としてもCubeは連続的に動かず、Alt+Pを押してからしばらくしていきなり(10,0,0)の位置に動いてしまいます。スレッドで動かせばいいのかと思い、下のようにしましたが、これでもだめです。

import bpy
from mathutils import *
import time
import threading

print('start******************')


class test(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self.i = 0

    def run(self):
        print("Thread Start.")
        bpy.data.objects["Cube"].location = (0,0,0)
        duration = 0.3
        time.sleep(duration)
       
        for i in range(10):
            bpy.data.objects["Cube"].location += Vector((1.0,0,0))
            time.sleep(duration)
       
        time.sleep(1)

        for i in range(10):
            bpy.data.objects["Cube"].location -= Vector((1.0,0,0))
            time.sleep(duration)

if __name__ == "__main__":
    t = test()
    t.start()
    time.sleep(30)

Cubeが動くごとにRedrawとかするのでしょうか?

と思って調べたらRedrawはしない方がいいみたいです。ここ

Tools that lock Blender in a loop and redraw are highly discouraged since they conflict with Blenders ability to run multiple operators at once and update different parts of the interface as the tool runs.

とあり、

So the solution here is to write a modal operator, that is - an operator which defines a modal() function, See the modal operator template in the text editor.

modal operatorを使うのが推奨されています。ということで今後modal operatorを調べることにします。

0 件のコメント: