Search Unity

Rotating around and following an object

Discussion in 'Scripting' started by Harrk, May 5, 2014.

  1. Harrk

    Harrk

    Joined:
    Oct 11, 2013
    Posts:
    16
    Hi guys,

    I'm having a problem getting my camera to rotate around my player from a fixed distance whilst following the player. This is the code I'm using so far to follow the player. The only thing missing is the rotation which I can't seem to figure out - I've tried a few different solutions from Google but none seem to work for me. Any help would be appreciated, thanks!

    Also I want to do this through code, and not by simply attaching the camera to the player.

    Code (csharp):
    1.  
    2. void Start () {
    3.         relativePosition = transform.position - Camera.main.transform.position;
    4. }
    5.  
    6. void Update () {
    7.         Camera.main.transform.LookAt(transform.position);
    8.         Camera.main.transform.position = transform.position - relativePosition;
    9. }
    10.  
     
  2. Harrk

    Harrk

    Joined:
    Oct 11, 2013
    Posts:
    16
    Just an update. I solved the problem by taking a look at the 3rd person camera script provided with Unity, here's the solution:

    Code (csharp):
    1.  
    2. Camera.main.transform.position = transform.position;
    3. Camera.main.transform.position += currentRotation * Vector3.back * 10;
    4. Camera.main.transform.position += new Vector3(0f, 4f, 0f);
    5. Camera.main.transform.LookAt (transform.position);
    6.  
    Thanks!