I am trying to make a modal operator that can track an object to the mouse location:
https://i.imgur.com/1uujJCq.mp4
I have this example for snapping(volume) an empty within an object, it works great(by Jeacom) & would like the empty to automatically track towards the cursors direction.
Here is the modal I have at the moment:
import bpy
from bpy_extras.view3d_utils import (region_2d_to_origin_3d,
region_2d_to_vector_3d)
def cursor_create(context):
bpy.ops.object.empty_add(type="SPHERE")
context.active_object.show_in_front = True
return context.active_object
def mouse_ray_get(context, event):
co = event.mouse_region_x, event.mouse_region_y
region = context.region
r_data = context.space_data.region_3d
origin = region_2d_to_origin_3d(region, r_data, co)
direction = region_2d_to_vector_3d(region, r_data, co)
return origin, direction
class TestSnap(bpy.types.Operator):
bl_idname = "object.test_snaping"
bl_label = "Test Snaping"
bl_options = {"REGISTER", "UNDO"}
cursor = None
def invoke(self, context, event):
self.cursor = cursor_create(context)
self._timer = context.window_manager.modal_handler_add(self)
return {"RUNNING_MODAL"}
def modal(self, context, event):
origin, direction = mouse_ray_get(context, event)
hit1, location1, normal, index, object, mat =\
context.scene.ray_cast(context.view_layer, origin, direction)
if hit1:
hit2, location2, normal, index, object, mat =\
context.scene.ray_cast(context.view_layer, location1 - 0.00001 * normal, -normal)
if hit2:
self.cursor.location = (location1 + location2) / 2
radius = (location1 - location2).length / 2
self.cursor.scale.x = radius
self.cursor.scale.y = radius
self.cursor.scale.z = radius
if event.type == "ESC":
return {"FINISHED"}
return {"PASS_THROUGH"}
bpy.utils.register_class(TestSnap)
Thanks