To get the direction vector of a 3D viewport, for example, to determine the location of the viewport relative to some object in the scene, we can use the region_2d_to_vector_3d function from the view3d_utils module.
To get the view direction vector from the viewport using the region_2d_to_vector_3d function, first, we need to determine the pointer to the area of the 3D viewport.
Loop through the open areas until we find the 3D viewport area:
1 2 |
for area in bpy.context.screen.areas: if area.type == 'VIEW_3D': |
Next, we need to get a pointer to the region of the viewport area. To find it, loop through the regions in the same way:
1 2 |
for region in area.regions: if region.type == 'WINDOW': |
Having received a pointer to the area region, we can call the region_2d_to_vector_3d function for it, which will return the desired view direction vector to us:
1 2 3 4 5 6 7 |
viewport_view_direction = view3d_utils.region_2d_to_vector_3d( region, region.data, (region.width / 2.0, region.height / 2.0) ) # <Vector (-0.0000, 1.0000, 0.0000)> |
In the function parameters we pass:
- region – a pointer to the region we found
- region.data – a pointer to the data of this region
- the center of the current region – the point from which the view direction is calculated
As a result, we get a normalized vector directed from the central point of the 3D viewport along its view direction.
For example, for a frontal view – when we look at an object from the front, the resulting view vector will be directed along the Y axis and have a length equal to 1:
(-0.0000, 1.0000, 0.0000)