I would like to constraint an object (cube) to the viewport camera, so it will be always in user's field of view. Is it possible with constraints (I didn't find any way) ? I also tried with python to get 3d coords :
import bpy
from bpy.props import IntProperty, FloatProperty
import bpy_extras
from mathutils import Vector, geometry
import mathutils
class ModalOperator(bpy.types.Operator):
"""Move an object with the mouse, example"""
bl_idname = "object.modal_operator"
bl_label = "Simple Modal Operator"
first_mouse_x: IntProperty()
first_value: FloatProperty()
def modal(self, context, event):
if event.type in {'MIDDLEMOUSE', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE'}:
coord = self.get_view_coord(context)
print("coord = ", coord)
return {'PASS_THROUGH'}
elif event.type in {'RIGHTMOUSE', 'ESC'}:
context.object.location.x = self.first_value
return {'CANCELLED'}
return {'RUNNING_MODAL'}
def invoke(self, context, event):
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
def get_view_coord(self,context):
region = bpy.context.region
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
rv3d = area.spaces.active.region_3d
break
pos = bpy_extras.view3d_utils.region_2d_to_location_3d( region, rv3d, Vector((100,500)), Vector((0,0,0)) )
orient = bpy_extras.view3d_utils.region_2d_to_vector_3d( region, rv3d, Vector((100,500)))
bpy.ops.object.empty_add(type='ARROWS', location= pos)
bpy.context.object.rotation_mode = 'QUATERNION'
bpy.context.object.rotation_quaternion = orient.to_track_quat('Z','Y')
return pos
def register():
bpy.utils.register_class(ModalOperator)
def unregister():
bpy.utils.unregister_class(ModalOperator)
if __name__ == "__main__":
register()
# test call
bpy.ops.object.modal_operator('INVOKE_DEFAULT')
Edit 1 : The final goal is to have several controller objects on the sides of 3d viewport, so I can manipulate them and via handlers, tweaking previously generated curves.
Edit 2 : With this modal example, I can have an empty placed in 3d viewport, but still don't know how to follow camera, how to get height and width of 3d area (to place it at the top left corner for example), plus Z axis is well oriented, but I would like Y axis to be parallel to the border of the screen.
view_matrix
belongs to the 3d region of active space of a 3d view area ie ifa
is area of type ``VIEW_3D'` thena.spaces.active.region_3d.view_matrix
whereas error is telling youcontext.region_data is None
and hence has no properties. Suggest editing to clarify the desired result, should object of interest face view, fill view, be in middle of view.. $\endgroup$