Search Unity

Make camera follow object that is going around a circle

Discussion in 'Scripting' started by dlockard, Jun 29, 2020.

  1. dlockard

    dlockard

    Joined:
    Jun 10, 2020
    Posts:
    2
    I have a ball rotating around a ring and I would like the camera to follow the ball in the same orientation as below. Where the camera is up at an angle from the ball with the surface of the ring on the bottom of the screen. UnityCameraHelp2.PNG
    I have tried several ways to get this to work. One of the ways being with a Cinemachine Dolly track but the camera always rotates its orientation and the view becomes flipped from what I want. I have also tried rotating around the center of gravity point (seen in the middle of the circle) but the camera is always out of sync with the ball no matter what I do. Any suggestions?
    UnityCameraHelp1.PNG
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    I would create a child object of the ball so it follows the balls position, but I would give it a script which does something like this:

    Code (CSharp):
    1. void LateUpdate() {
    2.   Vector3 centerOfRing = /** fill this in with the center of your ring **/
    3.   Vector3 outFromCenter = transform.position - centerOfRing;
    4.   transform.LookAt(transform.forward, outFromCenter);
    5. }
    So now the ball can roll freely, but this child object will always be oriented properly. This will work if you only need the ball to be on the "outside" edge of the ring. If you want the ball to be able to spin around the whole donut bit (including the inside), you will probably want to do a raycast to the ring and use the surface normal instead of get your "up" orientation.

    Then you can either just make the camera a child of that object, or use that object as the Cinemachine Virtual Camera's body target with something like a plain transposer with a Lock To Target binding mode. You might need to mess with script execution order to ensure that this script runs before Cinemachine's late updater unfortunately.
     
    Last edited: Jun 29, 2020
  3. dlockard

    dlockard

    Joined:
    Jun 10, 2020
    Posts:
    2
    Thanks for the reply PraetorBlue!

    I think it's a step in the right direction. There were two things that kind of didnt seem right with this implementation. First, when I set up this code for some reason the camera was looking at the opposite direction of the ball: UnityCameraHelp3.PNG Second, the camera did start to rotate eventually when the ball got under it. I am looking to get something like this, but following the ball instead of just rotating around the x axis freely.
     

    Attached Files: