operator_modal.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import bpy
  2. from bpy.props import IntProperty, FloatProperty
  3. class ModalOperator(bpy.types.Operator):
  4. """Move an object with the mouse, example"""
  5. bl_idname = "object.modal_operator"
  6. bl_label = "Simple Modal Operator"
  7. first_mouse_x: IntProperty()
  8. first_value: FloatProperty()
  9. def modal(self, context, event):
  10. if event.type == 'MOUSEMOVE':
  11. delta = self.first_mouse_x - event.mouse_x
  12. context.object.location.x = self.first_value + delta * 0.01
  13. elif event.type == 'LEFTMOUSE':
  14. return {'FINISHED'}
  15. elif event.type in {'RIGHTMOUSE', 'ESC'}:
  16. context.object.location.x = self.first_value
  17. return {'CANCELLED'}
  18. return {'RUNNING_MODAL'}
  19. def invoke(self, context, event):
  20. if context.object:
  21. self.first_mouse_x = event.mouse_x
  22. self.first_value = context.object.location.x
  23. context.window_manager.modal_handler_add(self)
  24. return {'RUNNING_MODAL'}
  25. else:
  26. self.report({'WARNING'}, "No active object, could not finish")
  27. return {'CANCELLED'}
  28. def register():
  29. bpy.utils.register_class(ModalOperator)
  30. def unregister():
  31. bpy.utils.unregister_class(ModalOperator)
  32. if __name__ == "__main__":
  33. register()
  34. # test call
  35. bpy.ops.object.modal_operator('INVOKE_DEFAULT')