Doing the maths for an orbit with a changing plane of rotation hurts my head just thinking about it. This is how I would do it, avoiding any maths:
sync on
make matrix 1,100,100,10,10
position matrix 1,-50,0,-50
make object cube 1,5
make object cube 2,1
hide object 2
do
turn object left 2,mousemovex()
pitch object up 2,mousemovey()
position camera object position x(2),object position y(2),object position z(2)
set camera to object orientation 2
move camera -20
point camera object position x(2),object position y(2),object position z(2)
sync
loop