0
$\begingroup$

I want to do something when the mouse moves over an object, so I want to know how to detect if the mouse moves over that object?

$\endgroup$
2
  • $\begingroup$ Since ray casting doesn't work on non-mesh objects like cameras, curves, etc. This is an operator that works on all visible object types: blender.stackexchange.com/questions/52142/… $\endgroup$
    – X Y
    Nov 11, 2023 at 8:33
  • $\begingroup$ Yes, you have a good complementation ! $\endgroup$
    – fage
    Nov 13, 2023 at 2:17

1 Answer 1

1
$\begingroup$

You need ray cast for that. For example, the following will detect everytime the mouse moves to a new screen X/Y location, throw out a ray from under your mouse and return some information about what object it hit.
See here for more info: https://docs.blender.org/api/3.5/bpy.types.Scene.html#bpy.types.Scene.ray_cast

hit is a boolean that returns True if an object is detected under the mouse coordinates

   def modal(self, context, event):
    
          if event.type == "MOUSEMOVE":
          if event.mouse_prev_x != event.mouse_x or event.mouse_prev_y != event.mouse_y:
    
          hit, face_location, face_normal, face_index, face_object, face_matrix = self.cast_ray(context, event)
          if hit:
                if face_object.type == 'MESH':
                      print("face_object", face_object)
                      print("face_location", face_location)
                      print("face_normal", face_normal)
                      print("face_index", face_index)
                      print("face_matrix", face_matrix)
    
    
    
    def cast_ray(self, context, event):
    
          # cast ray from mouse location, return data from ray
          scene = context.scene
          region = context.region
          rv3d = context.region_data
          coord = event.mouse_region_x, event.mouse_region_y
          viewlayer = context.view_layer.depsgraph
          # get the ray from the viewport and mouse
          view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)
          ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)
    
          hit, location, normal, index, object, matrix = scene.ray_cast(viewlayer, ray_origin, view_vector)
          return hit, location, normal, index, object, matrix
$\endgroup$
1
  • $\begingroup$ oh yes ! How you know this api ! That's very userful. $\endgroup$
    – fage
    Nov 13, 2023 at 2:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .