Search Unity

  1. Are you interested in providing feedback directly to Unity teams? Sign up to become a member of Unity Pulse, our new product feedback and research community.
    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:
    802
    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.. ^^



     
  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);
     
    mfaizanattique likes 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 Moderator

    Joined:
    Apr 11, 2010
    Posts:
    27,785
    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
     
  23. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    27,785
    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
     
    HHThehaotian likes this.
  28. HHThehaotian

    HHThehaotian

    Joined:
    Mar 17, 2020
    Posts:
    1
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEditor;
    public class CameraRotator : MonoBehaviour
    {
    public Transform target;
    public Camera mainCamera;
    [Range(0.1f, 5f)]
    [Tooltip("How sensitive the mouse drag to camera rotation")]
    public float mouseRotateSpeed = 0.8f;
    [Range(0.01f, 100)]
    [Tooltip("How sensitive the touch drag to camera rotation")]
    public float touchRotateSpeed = 17.5f;
    [Tooltip("Smaller positive value means smoother rotation, 1 means no smooth apply")]
    public float slerpValue = 0.25f;
    public enum RotateMethod { Mouse, Touch };
    [Tooltip("How do you like to rotate the camera")]
    public RotateMethod rotateMethod = RotateMethod.Mouse;
    private Vector2 swipeDirection; //swipe delta vector2
    private Quaternion cameraRot; // store the quaternion after the slerp operation
    private Touch touch;
    private float distanceBetweenCameraAndTarget;
    private float minXRotAngle = -80; //min angle around x axis
    private float maxXRotAngle = 80; // max angle around x axis
    //Mouse rotation related
    private float rotX; // around x
    private float rotY; // around y
    private void Awake()
    {
    if (mainCamera == null)
    {
    mainCamera = Camera.main;
    }

    }
    // Start is called before the first frame update
    void Start()
    {
    distanceBetweenCameraAndTarget = Vector3.Distance(mainCamera.transform.position, target.position);
    }
    // Update is called once per frame
    void Update()
    {
    if (rotateMethod == RotateMethod.Mouse)
    {
    if (Input.GetMouseButton(0))
    {
    rotX += -Input.GetAxis("Mouse Y") * mouseRotateSpeed; // around X
    rotY += Input.GetAxis("Mouse X") * mouseRotateSpeed;
    }
    if (rotX < minXRotAngle)
    {
    rotX = minXRotAngle;
    }
    else if (rotX > maxXRotAngle)
    {
    rotX = maxXRotAngle;
    }
    }
    else if (rotateMethod == RotateMethod.Touch)
    {
    if (Input.touchCount > 0)
    {
    touch = Input.GetTouch(0);
    if (touch.phase == TouchPhase.Began)
    {
    //Debug.Log("Touch Began");
    }
    else if (touch.phase == TouchPhase.Moved) // the problem lies in we are still rotating object even if we move our finger toward another direction
    {
    swipeDirection += touch.deltaPosition * Time.deltaTime * touchRotateSpeed;
    }
    else if (touch.phase == TouchPhase.Ended)
    {
    //Debug.Log("Touch Ended");
    }
    }
    if (swipeDirection.y < minXRotAngle)
    {
    swipeDirection.y = minXRotAngle;
    }
    else if (swipeDirection.y > maxXRotAngle)
    {
    swipeDirection.y = maxXRotAngle;
    }
    }
    }
    private void LateUpdate()
    {
    Vector3 dir = new Vector3(0, 0, -distanceBetweenCameraAndTarget); //assign value to the distance between the maincamera and the target
    Quaternion newQ; // value equal to the delta change of our mouse or touch position
    if (rotateMethod == RotateMethod.Mouse)
    {
    newQ = Quaternion.Euler(rotX , rotY, 0); //We are setting the rotation around X, Y, Z axis respectively
    }
    else
    {
    newQ = Quaternion.Euler(swipeDirection.y , -swipeDirection.x, 0);
    }
    cameraRot = Quaternion.Slerp(cameraRot, newQ, slerpValue); //let cameraRot value gradually reach newQ which corresponds to our touch
    mainCamera.transform.position = target.position + cameraRot * dir;
    mainCamera.transform.LookAt(target.position);
    }
    public void SetCamPos()
    {
    if(mainCamera == null)
    {
    mainCamera = Camera.main;
    }
    mainCamera.transform.position = new Vector3(0, 0, -distanceBetweenCameraAndTarget);
    }
    }


    This is my solution to the problem, check it out, the code should be self-explanatory.
    You can rotate the camera using a mouse or a touch device running Unity Remote5.
     
    nakrufrats likes this.
unityunity