Pick an object in a modal operator

Hello everyone,

In the 3d view, I have a selected object, I’d like to snap it to another object in a modal operator. This is the script I have for the moment but I don’t know how to get the object (and its face) that is pointed by the mouse when leftmouse is pressed.


    def modal(self, context, event):
        
        w = context.window_manager.windows[0]
        w.cursor_modal_set("EYEDROPPER")
        
        context.area.tag_redraw()

        if event.type == 'LEFTMOUSE':
            mouse_x = event.mouse_x - context.region.x
            mouse_y = event.mouse_y - context.region.y
            
            
            print (context.object.name) # object to snap where the mouse is on te screen
            print (mouse_x, mouse_y) # position of the mouse in the screen, but how to get object behind it?
            
            
            w.cursor_modal_restore()
            return {'FINISHED'}

Also, I’d like to constantly run the script when the mouse is pressed. I tried to replace {“FINISHED”} by {“RUNNING_MODAL”} but the script is executed only twice : when the mouse button is pressed and released. Is it possible to run it each time the mouse is pressed and the mouse is moving for example?

Thank you!!

may be you should add some “def” that check the new one object selected…



def checknewselected():
     #here the code that check new selected object

if event.type == 'LEFTMOUSE':
            mouse_x = event.mouse_x - context.region.x 
            mouse_y = event.mouse_y - context.region.y
#here you call the "def"
            checknewselected() 




I don’t want to select another object. I want keep my selection, and snap it where other objects are under the mouse position.

Why do you need a custom operator for that? Can’t you use Blender’s built-in snapping support?

Macros are definitely an option to invoke a built-in transformation with custom settings.

I want to do more than only that of course, it’s just to start :wink:

I’d like to have a tool to place lights easily depending of the angle of the face with an offset.
I did it for Nuke and it’s incredibly useful for me, to create rim light or lamp that has to be perfectly align to one face. I’d like to do something similar in Blender and what I would need to get is the normal of the face where the mouse button is pressed.

You’ll probably have to implement the entire snapping yourself in Python. Have a look at the template scripts, there’s a ray casting example.

Too much work, although doable. (See some of my recent answers, they are relevant. In one I show how to obtain camera coordinates of points, in another how to get world coordinates to drive one thing from another.) I would take a different approach, easier to script and then use. Assume you’re in edit mode on the object, with the face selected - script it from there. That way you don’t need a modal operator and the (relatively) slow process of iterating through objects and faces.