I want to place an object where the cursor is using python. So I need a script that place the 3D cursor where I have the cursor at that moment and then place the already selected object there. To do that I created a quick favorite that call that script loaded as addon (image below)
But I can't get the 3D cursor where the "windows cursor" is pointing. I'd need a script that emulate what the shift+RMB does
I'm just a newbie, please have mercy :) since my code may be neither elegant nor good
bl_info = {
"name": "Place object",
"blender": (4, 0 ,2),
"category": "Object",
}
import bpy
import mathutils
class OBJECT_OT_placeObject(bpy.types.Operator):
"""Place object where the cursor is"""
bl_idname = "object.place"
bl_label = "Place Object"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
# Mouse cursor coordinates
mouse_x = bpy.context.region.width // 2
mouse_y = bpy.context.region.height // 2
# Get the depsgraph actual
depsgraph = bpy.context.evaluated_depsgraph_get()
# Convert mouse coordinates to a ray in 3D space
ray = bpy.context.scene.ray_cast(depsgraph, origin=bpy.context.area.spaces[0].region_3d.view_location, direction=mathutils.Vector((mouse_x, mouse_y, 0.0)))
# test if ray intersetcs
if ray[0]:
# Mover 3D where the mouse cursor is pointing
bpy.context.scene.cursor.location = ray[1]
else:
print("No se encontró intersección")
# -----------------------------------------------------------
# Place object where the cursor is
# Get the 3D cursor position
cursor_location = bpy.context.scene.cursor.location
# Get the selected object
selected_object = bpy.context.selected_objects[0]
# Move selected object where the 3D cursor is
selected_object.location = cursor_location
def menu_func(self, context):
self.layout.operator(OBJECT_OT_placeObject.bl_idname)
def register():
bpy.utils.register_class(OBJECT_OT_placeObject)
bpy.types.VIEW3D_MT_object.append(menu_func)
def unregister():
bpy.utils.unregister_class(OBJECT_OT_placeObject)
if __name__ == "__main__":
register()
```