title: Elliptical Rotation on touch (or click) in Unity
body: <p>I'm making a camera that rotates around an egg. I can't figure out how to do that. The rotation has clamps at -90 +90 on x and y each. I made a code that changes the camera position based on the current x rotation of the pivot but it doesn't give me an accurate result. This is the code for that:</p>
  <pre><code>using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  public class CameraMotionScript : MonoBehaviour {
  
      public Transform thePivot, theCamera;
      public float rotSpeed = 5f, lerpSpeed, minX, maxX, minY, maxY, maxDist, divRatio;
  
      private float   rotX = 0f,
                      rotY = 0f,
                      dX = 0f,
                      dY = 0f,
                      rotateDirection = -1f,
                      cachedRotSpeed = 0f,
                      minDist = 0f;
  
      private bool rotationActive = false;
  
      void Start () {
          cachedRotSpeed = rotSpeed;
          minDist = Mathf.Abs (theCamera.localPosition.z);
          divRatio = maxX / maxDist;
      }
  
      void Update () {
  
          if (Input.GetMouseButton (0)) {
              rotSpeed = cachedRotSpeed;
              dX = Input.GetAxis (&quot;Mouse X&quot;);
              dY = Input.GetAxis (&quot;Mouse Y&quot;);
              rotationActive = true;
          }
  
          if (Input.GetMouseButtonUp (0)) {
              rotationActive = false;
          }
  
          rotX += dY * rotSpeed * rotateDirection * Time.deltaTime;
          rotY += dX * rotSpeed * -rotateDirection * Time.deltaTime;
  
          rotX = Mathf.Clamp (rotX, minX, maxX);
          rotY = Mathf.Clamp (rotY, minY, maxY);
  
          if (thePivot != null)
              thePivot.eulerAngles = new Vector3 (rotX, rotY, 0f);
  
          if (!rotationActive) {
              rotSpeed = Mathf.Lerp (rotSpeed, 0, Time.deltaTime * lerpSpeed);
              if (rotSpeed &lt; 1)
                  rotSpeed = 0;
          }
  
          MaintainDistanceAt (Mathf.Abs (rotX));
      }
  
      void MaintainDistanceAt (float f) {
          if (f != 0) {
              float zVal = f / divRatio;
              if (zVal &lt; minDist)
                  zVal = minDist;
              theCamera.localPosition = new Vector3 (0f, 0f, zVal * -1f);
          }
      }
  }
  </code></pre>
  <p>For this code my camera is the child of the pivot and I rotate the pivot with the mouse click. I take in the x rotation of the pivot and calculate the distance of the camera. I modify it based on the run time x rotation of the pivot.
  I've added smooth speed code in it too but ignore that for now.</p>
  <p>So the problem is, the distance code that I wrote sets the position of the camera in a linear vector, so it cuts through the egg mesh and clips it.</p>
  <p>I want to be able to move the camera in an elliptical orbit around the egg.
  Any suggestions on how do I solve this?
  Thanks in advance.</p>