Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Rotate the camera around the object.

Discussion in 'Scripting' started by DarkSoul, Apr 26, 2010.

  1. DarkSoul

    DarkSoul

    Joined:
    Dec 24, 2009
    Posts:
    37
    Hello.
    I want to rotate the camera around the object, but this is something that never I have been given well. I'm using "Mathf.LerpAngle", but I think that I don't know use this, any help or orientation, please?

    Thanks.
     
    hopetolive, gazorpeth and Renoten like this.
  2. SarperS

    SarperS

    Joined:
    Mar 10, 2009
    Posts:
    824
    Make the camera look at the object, then add a movement to it in Update function.

    Add the below code to your camera, and set the target to the object in unity inspector window.

    Code (csharp):
    1. var target:transform;
    2.  
    3. function Update(){
    4.     transform.LookAt(target);
    5.     transform.Translate(Vector3.right * Time.deltaTime);
    6. }
     
  3. DarkSoul

    DarkSoul

    Joined:
    Dec 24, 2009
    Posts:
    37
    Ok, I will try, thanks!
     
  4. gharaibeh

    gharaibeh

    Joined:
    Apr 26, 2011
    Posts:
    115
    Mortiis, Grate thanks man, this is the desired simplest code :)
     
  5. Muhammad Fahad

    Muhammad Fahad

    Joined:
    Aug 19, 2011
    Posts:
    9
    give me a code that rotate camera left and right both sides concurently around tareget object

    transform.Translate(Vector3.left * Time.deltaTime); and \transform.Translate(Vector3.right * Time.deltaTime);

    you code only moves arooound left side....;)





     
  6. Muhammad Fahad

    Muhammad Fahad

    Joined:
    Aug 19, 2011
    Posts:
    9
    i have a project on unity can i send you to give me help !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     
  7. matheusUnity

    matheusUnity

    Joined:
    May 1, 2012
    Posts:
    1
    Well, I tried it and it came up a bug...

    Applying a speed modifier to the translation I figured that when you make the object look at a target and translate it at some axis, something happens that the radius between the object and its target goes increasing along the time, and it makes the object going far from its target. Maybe UnityEngine increases the axis more than once before updating the object's rotation.

    I got better results using something like this:

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class CameraClass : MonoBehaviour {
    5.    
    6.     public TargetClass target;//the target object
    7.     private float speedMod = 10.0f;//a speed modifier
    8.     private Vector3 point;//the coord to the point where the camera looks at
    9.    
    10.     void Start () {//Set up things on the start method
    11.         point = target.transform.position;//get target's coords
    12.         transform.LookAt(point);//makes the camera look to it
    13.     }
    14.    
    15.     void Update () {//makes the camera rotate around "point" coords, rotating around its Y axis, 20 degrees per second times the speed modifier
    16.         transform.RotateAround (point,new Vector3(0.0f,1.0f,0.0f),20 * Time.deltaTime * speedMod);
    17.     }
    18. }
    19.  
    Sorry for the code in C#, I prefer using it because it is more strong typed and Object Oriented... but it is easy to port it to javascript too.. ^^



     
    nhnazari, Dominus12, salihtok and 5 others like this.
  8. amit.r007

    amit.r007

    Joined:
    Jun 1, 2013
    Posts:
    17
    Thanks, This is what I was looking for.... :)
     
  9. GaneshDeveloper

    GaneshDeveloper

    Joined:
    Feb 14, 2014
    Posts:
    4
    I want to rotate the camera based on user touchmovement. so that I have show my 3d model in 360 degree to user how can I achieve this?
    please help for me too. thanks,
     
  10. ClaasM

    ClaasM

    Joined:
    Oct 4, 2014
    Posts:
    26
    Do NOT use
    Code (CSharp):
    1. transform.Translate(Vector3.right * Time.deltaTime);
    as it will slowly move vour camera away from the object you're rotating around.
    Instead, use
    Code (CSharp):
    1. transform.RotateAround (object.transform.position, Vector3.up, speed * Time.deltaTime);
     
    CringeItIn, zanouk and mfaizanattique like this.
  11. Fragmental

    Fragmental

    Joined:
    Jun 30, 2013
    Posts:
    61
    I'm confused by this. What is TargetClass? It doesn't exist.

    Edit: Still not sure what "TargetClass" is, but I changed "TargetClass" to "GameObject", and found my object in the scene. Works now.
     
    Last edited: Oct 6, 2014
    mumenthaler-michi likes this.
  12. phxvyper

    phxvyper

    Joined:
    Jul 31, 2012
    Posts:
    8
    Fragmental, What he sent you is a pseudo code. TargetClass can be any MonoBehaviour attached to your GameObject, including the GameObject class! I almost always use GameObject for "target" types.
     
    Fragmental likes this.
  13. mfaizanattique

    mfaizanattique

    Joined:
    Jan 27, 2015
    Posts:
    5
    Koool buddy you saved me
     
  14. softnax

    softnax

    Joined:
    Mar 20, 2015
    Posts:
    6
    hi

    Make Sure you add the LookAt line after the Translate Line.. for some cases it will jerk the cam.

    Code (csharp):
    1. var target:transform;
    2.  
    3. function Update(){
    4.     transform.Translate(Vector3.right * Time.deltaTime);
    5.     transform.LookAt(target);
    6.  
    7. }
    [/QUOTE]
     
  15. Sharpless512

    Sharpless512

    Joined:
    Jan 16, 2014
    Posts:
    1
    Awesome!!
     
  16. XenonSpher

    XenonSpher

    Joined:
    Dec 11, 2015
    Posts:
    29
    please watch this video.


    its short but the concept is straight forward. its the edit scene in unity where you can rotate around an object and zoom on it or what not.

    How do you create this feature in in-game not in edit scene but in-game. do the above notes help?
     
  17. JeremyGames

    JeremyGames

    Joined:
    Jul 4, 2014
    Posts:
    21
    Bump. 1st script is broken now.
     
    Behnam-13 likes this.
  18. WhitishMink

    WhitishMink

    Joined:
    Sep 14, 2017
    Posts:
    1
    New code:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class CameraClass : MonoBehaviour {
    4.  
    5.     public GameObject target;//the target object
    6.     private float speedMod = 10.0f;//a speed modifier
    7.     private Vector3 point;//the coord to the point where the camera looks at
    8.  
    9.     void Start () {//Set up things on the start method
    10.         point = target.transform.position;//get target's coords
    11.         transform.LookAt(point);//makes the camera look to it
    12.     }
    13.  
    14.     void Update () {//makes the camera rotate around "point" coords, rotating around its Y axis, 20 degrees per second times the speed modifier
    15.         transform.RotateAround (target.transform.position, Vector3.up, speedMod * Time.deltaTime);  
    16.     }
    17. }
    Just put the GameObject you wish to rotate around in the target slot in Inspector.

    Tested working in 5.5.3f1
     
    the_motionblur, Renoten and Cookieg82 like this.
  19. Cookieg82

    Cookieg82

    Joined:
    Mar 28, 2017
    Posts:
    73
    How would you adapt this to stop the rotation at a certain degrees, say 90 or rotate -90 using a collider the player walks or rolls into?
     
  20. Zythus

    Zythus

    Joined:
    Jun 28, 2014
    Posts:
    30
    Try tinkering with bools = if (collidedWithThing)
     
    Cookieg82 likes this.
  21. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    Play nice, everyone.
     
  22. Cookieg82

    Cookieg82

    Joined:
    Mar 28, 2017
    Posts:
    73
    I am confused, what exactly happened in this thread? I cannot see any flaming or issues here? I have an alert to say I was insulting someone? I do not recall ever doing this? lol
     
    getzomeWare likes this.
  23. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    Mods delete things / ban things / etc. Not the droids you're looking for :)
     
  24. Frendall

    Frendall

    Joined:
    Aug 28, 2018
    Posts:
    1
    Hi there
    I'm pretty new to unity, and im most probably well over my head here. I put a follow script on my camera which works
    and then I decided to use right mouse click to rotate the camera using the script above, which also works. the problem is, the camera springs back to the original follow position. any help would be appreciated. thanks in advance.

    public class CamaraFollow : MonoBehaviour {
    public Transform target;

    public float smoothSpeed = 0.125f;

    public Vector3 offSet;
    public float rotateSpeed;


    private float speedMod = 10.0f;//a speed modifier
    private Vector3 point;//the coord to the point where the camera looks at
    private void FixedUpdate()
    {

    if (Input.GetMouseButton(1) == true)
    {
    //Set up things on the start method
    point = target.transform.position;//get target's coords
    transform.LookAt(point);//makes the camera look to it
    //makes the camera rotate around "point" coords, rotating around its Y axis, 4 degrees per second times the speed modifier
    transform.RotateAround(point, new Vector3(0.0f, 1.0f, 0.0f), 10 * Time.deltaTime * speedMod);
    Debug.Log("mouse down");
    }else
    {
    //Follow Player
    Vector3 desiredPosition = target.position + offSet;
    Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
    transform.position = smoothedPosition;
    transform.LookAt(target);
    }
    }

    }
     
    unity_PsYU5ZX6TLsoTg likes this.
  25. Deleted User

    Deleted User

    Guest

    Wouldn't fixed- or late update be better in this case? Or does it not matter?
     
  26. thorhammer2301

    thorhammer2301

    Joined:
    Jan 14, 2020
    Posts:
    10
    How can i rotate camera for FPS..as i'm a beginner..need help
     
  27. NetNerd

    NetNerd

    Joined:
    Oct 12, 2020
    Posts:
    2
    Watch
    I
    t's a Brackeys FIRST PERSON MOVEMENT IN UNITY
     
    Deleted User likes this.
  28. Deleted User

    Deleted User

    Guest

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEditor;
    5. //We want to intelligently distinguish whether we are currently at unity editor or not
    6. public class CameraController : MonoBehaviour
    7. {
    8.     //the center of the camera rotate sphere
    9.     public Transform target;
    10.     public Camera sceneCamera;
    11.  
    12.     [Range(5f, 15f)]
    13.     [Tooltip("How sensitive the mouse drag to camera rotation")]
    14.     public float mouseRotateSpeed = 5f;
    15.  
    16.     [Range(10f, 50f)]
    17.     [Tooltip("How sensitive the touch drag to camera rotation")]
    18.     public float touchRotateSpeed = 10f;
    19.  
    20.     [Tooltip("Smaller positive value means smoother rotation, 1 means no smooth apply")]
    21.     public float slerpSmoothValue = 0.3f;
    22.     [Tooltip("How long the smoothDamp of the mouse scroll takes")]
    23.     public float scrollSmoothTime = 0.12f;
    24.     public float editorFOVSensitivity = 5f;
    25.     public float touchFOVSensitivity = 5f;
    26.  
    27.     //Can we rotate camera, which means we are not blocking the view
    28.     private bool canRotate = true;
    29.  
    30.     private Vector2 swipeDirection; //swipe delta vector2
    31.     private Vector2 touch1OldPos;
    32.     private Vector2 touch2OldPos;
    33.     private Vector2 touch1CurrentPos;
    34.     private Vector2 touch2CurrentPos;
    35.     private Quaternion currentRot; // store the quaternion after the slerp operation
    36.     private Quaternion targetRot;
    37.     private Touch touch;
    38.  
    39.     //Mouse rotation related
    40.     private float rotX; // around x
    41.     private float rotY; // around y
    42.     //Mouse Scroll
    43.     private float cameraFieldOfView;
    44.     private float cameraFOVDamp; //Damped value
    45.     private float fovChangeVelocity = 0;
    46.  
    47.     private float distanceBetweenCameraAndTarget;
    48.     //Clamp Value
    49.     private float minXRotAngle = -85; //min angle around x axis
    50.     private float maxXRotAngle = 85; // max angle around x axis
    51.  
    52.     private float minCameraFieldOfView = 6;
    53.     private float maxCameraFieldOfView = 30;
    54.  
    55.     Vector3 dir;
    56.     private void Awake()
    57.     {
    58.         GetCameraReference();
    59.  
    60.     }
    61.     // Start is called before the first frame update
    62.     void Start()
    63.     {
    64.         distanceBetweenCameraAndTarget = Vector3.Distance(sceneCamera.transform.position, target.position);
    65.         dir = new Vector3(0, 0, distanceBetweenCameraAndTarget);//assign value to the distance between the maincamera and the target
    66.         sceneCamera.transform.position = target.position + dir; //Initialize camera position
    67.  
    68.         cameraFOVDamp = sceneCamera.fieldOfView;
    69.         cameraFieldOfView = sceneCamera.fieldOfView;
    70.     }
    71.  
    72.     // Update is called once per frame
    73.     void Update()
    74.     {
    75.         if (!canRotate)
    76.         {
    77.             return;
    78.         }
    79.         //We are in editor
    80.         if (Application.isEditor || Application.platform == RuntimePlatform.WindowsPlayer)
    81.         {
    82.             EditorCameraInput();
    83.         }
    84.         else //We are in mobile mode
    85.         {
    86.             TouchCameraInput();
    87.         }
    88.  
    89.         if (Input.GetKeyDown(KeyCode.F))
    90.         {
    91.             FrontView();
    92.         }
    93.         if (Input.GetKeyDown(KeyCode.T))
    94.         {
    95.             TopView();
    96.         }
    97.         if (Input.GetKeyDown(KeyCode.L))
    98.         {
    99.             LeftView();
    100.         }
    101.  
    102.     }
    103.  
    104.     private void LateUpdate()
    105.     {
    106.         RotateCamera();
    107.         SetCameraFOV();
    108.     }
    109.  
    110.     public void GetCameraReference()
    111.     {
    112.         if (sceneCamera == null)
    113.         {
    114.             sceneCamera = Camera.main;
    115.         }
    116.  
    117.     }
    118.  
    119.     //May be the problem with Euler angles
    120.     public void TopView()
    121.     {
    122.         rotX = -85;
    123.         rotY = 0;
    124.     }
    125.  
    126.     public void LeftView()
    127.     {
    128.         rotY = 90;
    129.         rotX = 0;
    130.     }
    131.  
    132.     public void FrontView()
    133.     {
    134.         rotX = 0;
    135.         rotY = 0;
    136.     }
    137.  
    138.     private void EditorCameraInput()
    139.     {
    140.         //Camera Rotation
    141.         if (Input.GetMouseButton(0))
    142.         {
    143.             rotX += Input.GetAxis("Mouse Y") * mouseRotateSpeed; // around X
    144.             rotY += Input.GetAxis("Mouse X") * mouseRotateSpeed;
    145.  
    146.             if (rotX < minXRotAngle)
    147.             {
    148.                 rotX = minXRotAngle;
    149.             }
    150.             else if (rotX > maxXRotAngle)
    151.             {
    152.                 rotX = maxXRotAngle;
    153.             }
    154.         }
    155.         //Camera Field Of View
    156.         if (Input.mouseScrollDelta.magnitude > 0)
    157.         {
    158.             cameraFieldOfView += Input.mouseScrollDelta.y * editorFOVSensitivity * -1;//-1 make FOV change natual
    159.         }
    160.     }
    161.  
    162.     private void TouchCameraInput()
    163.     {
    164.         if (Input.touchCount > 0)
    165.         {
    166.             if (Input.touchCount == 1)
    167.             {
    168.                 touch = Input.GetTouch(0);
    169.                 if (touch.phase == TouchPhase.Began)
    170.                 {
    171.                     //Debug.Log("Touch Began");
    172.  
    173.                 }
    174.                 else if (touch.phase == TouchPhase.Moved)  // the problem lies in we are still rotating object even if we move our finger toward another direction
    175.                 {
    176.                     swipeDirection += -touch.deltaPosition * touchRotateSpeed; //-1 make rotate direction natural
    177.                 }
    178.                 else if (touch.phase == TouchPhase.Ended)
    179.                 {
    180.                     //Debug.Log("Touch Ended");
    181.                 }
    182.             }
    183.             else if (Input.touchCount == 2)
    184.             {
    185.                 Touch touch1 = Input.GetTouch(0);
    186.                 Touch touch2 = Input.GetTouch(1);
    187.                 if (touch1.phase == TouchPhase.Began && touch2.phase == TouchPhase.Began)
    188.                 {
    189.  
    190.                     touch1OldPos = touch1.position;
    191.                     touch2OldPos = touch2.position;
    192.  
    193.                 }
    194.                 if (touch1.phase == TouchPhase.Moved && touch2.phase == TouchPhase.Moved)
    195.                 {
    196.                     touch1CurrentPos = touch1.position;
    197.                     touch2CurrentPos = touch2.position;
    198.                     float deltaDistance = Vector2.Distance(touch1CurrentPos, touch2CurrentPos) - Vector2.Distance(touch1OldPos, touch2OldPos);
    199.                     cameraFieldOfView += deltaDistance * -1 * touchFOVSensitivity; // Make rotate direction natual
    200.                     touch1OldPos = touch1CurrentPos;
    201.                     touch2OldPos = touch2CurrentPos;
    202.                 }
    203.  
    204.             }
    205.  
    206.         }
    207.  
    208.         if (swipeDirection.y < minXRotAngle)
    209.         {
    210.             swipeDirection.y = minXRotAngle;
    211.         }
    212.         else if (swipeDirection.y > maxXRotAngle)
    213.         {
    214.             swipeDirection.y = maxXRotAngle;
    215.         }
    216.  
    217.  
    218.     }
    219.  
    220.     private void RotateCamera()
    221.     {
    222.  
    223.         if (Application.isEditor || Application.platform == RuntimePlatform.WindowsPlayer)
    224.         {
    225.             Vector3 tempV = new Vector3(rotX, rotY, 0);
    226.             targetRot = Quaternion.Euler(tempV); //We are setting the rotation around X, Y, Z axis respectively
    227.         }
    228.         else
    229.         {
    230.             targetRot = Quaternion.Euler(-swipeDirection.y, swipeDirection.x, 0);
    231.         }
    232.         //Rotate Camera
    233.         currentRot = Quaternion.Slerp(currentRot, targetRot, Time.smoothDeltaTime * slerpSmoothValue * 50);  //let cameraRot value gradually reach newQ which corresponds to our touch
    234.         //Multiplying a quaternion by a Vector3 is essentially to apply the rotation to the Vector3
    235.         //This case it's like rotate a stick the length of the distance between the camera and the target and then look at the target to rotate the camera.
    236.         sceneCamera.transform.position = target.position + currentRot * dir;
    237.         sceneCamera.transform.LookAt(target.position);
    238.  
    239.     }
    240.  
    241.  
    242.     void SetCameraFOV()
    243.     {
    244.         //Set Camera Field Of View
    245.         //Clamp Camera FOV value
    246.         if (cameraFieldOfView <= minCameraFieldOfView)
    247.         {
    248.             cameraFieldOfView = minCameraFieldOfView;
    249.         }
    250.         else if (cameraFieldOfView >= maxCameraFieldOfView)
    251.         {
    252.             cameraFieldOfView = maxCameraFieldOfView;
    253.         }
    254.  
    255.         cameraFOVDamp = Mathf.SmoothDamp(cameraFOVDamp, cameraFieldOfView, ref fovChangeVelocity, scrollSmoothTime);
    256.         sceneCamera.fieldOfView = cameraFOVDamp;
    257.  
    258.     }
    259.  
    260. }
    261.  
    My latest approach, check it out :)
    You can rotate the camera using a mouse or a touch device connected to your computer, running Unity Remote5 or a mobile build.
     
    Last edited by a moderator: Nov 12, 2021
  29. saharsh1223

    saharsh1223

    Joined:
    Jun 20, 2021
    Posts:
    3
    thanks
     
  30. CoreCoder

    CoreCoder

    Joined:
    Jun 11, 2015
    Posts:
    42
    Super nice scripts! Thank you.