Skip to main content
2 of 3
edited tags
Blunder
  • 14.8k
  • 4
  • 16
  • 37

Adding camera in front of an object based on xyz rotation

About the script: I would like to add a camera in front of a selected object. The front of the object is based on a calculation using a pre-defined polarangle, azimuthal angle and distance.

The problem: When I rotate the selected object on the Y axis I can't compensate for it, the conversion between the Cartesian and Spheric coordinates resulting a wrongly added camera. It works when Y is 0.

I am using the following function to defined the xyz coordinates based on the distance and the angles from an object.

import bpy
import math

# https://planetcalc.com/7952/
def calculateDirectionPoint(distance,pol,az):
    # calculates the coordinates based on distance and angles (Spheric to Cartesian coordinates)
    x = distance * math.sin(pol) * math.cos(az)
    y = distance * math.sin(pol) * math.sin(az) 
    z = distance * math.cos(pol) 
    return [x,y,z]

I am using the following code to define the selected object location and the relevant angles.

# following object rotation
object = bpy.data.objects['Suzanne']
objrot = object.rotation_euler
o_x = objrot[0]
o_y = objrot[1]
o_z = objrot[2]

# FRONT x and z
#pol_x = 1.570796327
pol_x = math.radians(90)
#az_z = -1.570796327
az_z = math.radians(90)*-1

if o_y == 0:
    az_m = 0
    pol_m = 0
else:
    # This is the part where the I can't define the right correction for the o_y value from the object y rotation.
    pol_m = math.pi-o_x
    az_m = o_y*((math.pi/2)/o_y)
  
coord = calculateDirectionPoint(
    6,
    (pol_x+o_x)+pol_m,
    (az_z+o_z)+az_m
    )

cam = bpy.data.objects['Camera']
cam.location = (coord[0], coord[1], coord[2])
cam.rotation_euler = (pol_x+o_x, o_y, (az_z+math.pi/2)+o_z)

Can someone advise how should I compensate for the Y axis? Thanks.