Search code examples
unity-game-enginecamerarotation

How to rotate a Unity camera around an object in up-down direction with a degree input


left: slider with values from 0-90, center: desired cam movement from z-axis, right: cam angle towards target on the x-z-Axis

Given a single input angle, I would like to move a camera facing a target object from a top-down position (in the image: 90 degrees) to the bottom plane, along a curve like a sphere surface.

On the left side of the image (1) is a slider in up-down direction, emitting values from 0-90 (degrees). If the slider is at 45 degrees, the camera should move to a diagonal position like in the center of the image (2), if the slider is at 0, it should be at the floor, still facing the target object.

Please note the right part of the image (3), a top-down look at the situation: The camera could be anywhere along the x-z plane. The lines are the x-z angles between different camera positions and the target object. The camera should stay on this line when moving up or down.

I have the transform and position of the cam, the transform and position of the target object, the distance as Vector3 between the 2 positions, and an input angle in degrees from 0-90.

But I don't understand how I would get and use the angle(s) between the cam and the target. I couldn't find a complete example how to approach this, only fragments and so I'm lost between Euler angles, quaternions, transform.rotate, transform.rotation, AngleAxis, LookRotation and many other things Google threw my way to consider, such as arcball cameras.

Could someone give me a step-step example what is the right way to move the camera as described in the image? Something like

void moveCamUpDownToDegree(float degree, Camera cam, Transform centerObjectTransform) {
    Vector 3 newCamPosition;

    //how to calculate the new position?

    cam.transform.position = newCamPosition;
    //last line if needed
    cam.transform.LookAt(centerObjectTransform);
        
}

Thank you for any help.


Solution

  • More like an orbital system or something like a third person, actually it's not as difficult as it might seem, here's an example:

    enter image description here

    using UnityEngine;
    
    public class Sample : MonoBehaviour
    {
        public Transform target; //Purpose of the object
        public Vector2 angle; //Purpose of the object
        public Vector3 offset; //Purpose of the object
        public float distance = 5; //Distance
    
    
        private void Update()
        {
            Quaternion rotation = Quaternion.Euler(angle.x,angle.y,0); 
            Vector3 position = rotation * new Vector3(0, 0, -distance) + target.position + offset;
    
            transform.position = position;
            transform.rotation = rotation;
        }
    
    }