Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

[Solved] Camera scripting Zoom and Rotate around a target

Discussion in 'Scripting' started by nntvog, Nov 14, 2009.

  1. nntvog

    nntvog

    Joined:
    Nov 14, 2009
    Posts:
    6
    Hi am new to unity. I need helps creating a script that control the camera that behave like in a strategy game.
    Requirements:
    1. When I select a target the camera will move close to and focus on the new target.
      If I hold down and drag the mouse on the screen, camera will rotate based on the direction of the mouse.
      If I try to move the mouse to an edge of the screen, the camera will look at that direction
      IF I make a mouse scroll, rhe camera will get closer or farther away from the target
      The camera cannot get closer or farther than a predefined distance

    Here is what I think it should look something like this:
    Code (csharp):
    1.  
    2. var myTarget  : Transform;
    3. var myCamera : Transform;
    4. var minDistance : float; //min distance between the cam and target
    5. var maxDistance : float; // max distance
    6. var springness : float; //how fast the camera should move when the target change it position
    7. //some other variables
    8.  
    9. //somewhere in the code
    10. //To get the mouse drag
    11. if (Input.GetMouseButton(0)) {
    12. Input.GetAxis("Mouse X");
    13. Input.GetAxis("Mouse Y");
    14. }
    15.  
    Here is what i have learned to move the cam to a designed position
    Code (csharp):
    1.  
    2. myCamera.position = Vector3.Lerp (myCamera.position, newPosition, Time.deltaTime * springness);
    3.  
    However, I am struggling to find an appropriate position for the cam to move to when the target change.
    and also the camera to rotate when i drag around the target.
    Please help. A working script will be appreciated.
     
  2. nntvog

    nntvog

    Joined:
    Nov 14, 2009
    Posts:
    6
    I think I found the solution after seeing someone suggest checking for the mouseOrbit.js in the standard asset. I edited it to fit my need.

    I want to share it with you.
    Code (csharp):
    1.  
    2. //This code should attached to an empty object
    3. //I would name it "Camera Controller"
    4. var target : Transform;
    5. var camera : Transform; //In case you have more than one camera
    6. var distance = 10.0;
    7. var cameraSpeed = 5;
    8.  
    9. var xSpeed = 175.0;
    10. var ySpeed = 75.0;
    11.  
    12. var yMinLimit = 20; //Lowest vertical angle in respect with the target.
    13. var yMaxLimit = 80;
    14.  
    15. var minDistance = 5; //Min distance of the camera from the target
    16. var maxDistance = 20;
    17.  
    18. private var x = 0.0;
    19. private var y = 0.0;
    20.  
    21. @script AddComponentMenu("Camera-Control/Mouse Orbit")
    22.  
    23. function Start () {
    24.     var angles = camera.eulerAngles;
    25.     x = angles.y;
    26.     y = angles.x;
    27.  
    28.     // Make the rigid body not change rotation
    29.     if (rigidbody)
    30.         rigidbody.freezeRotation = true;
    31. }
    32.  
    33. function LateUpdate () {
    34.     if (target  camera) {
    35.  
    36.    //Zooming with mouse
    37.     distance += Input.GetAxis("Mouse ScrollWheel")*distance;
    38.     distance = Mathf.Clamp(distance, minDistance, maxDistance);
    39.  
    40.     //Detect mouse drag;
    41.     if(Input.GetMouseButton(0)) {
    42.    
    43.         x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
    44.         y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;        
    45.         }
    46.         y = ClampAngle(y, yMinLimit, yMaxLimit);
    47.                
    48.         var rotation = Quaternion.Euler(y, x, 0);
    49.         var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;
    50.    //When the target changed or moved, Move the camera smoothly with it.       
    51.    camera.position = Vector3.Lerp (camera.position, position, cameraSpeed*Time.deltaTime);
    52.         camera.rotation = rotation;
    53.         //camera.LookAt(target);
    54.        
    55.        
    56.     }
    57. }
    58.  
    59. static function ClampAngle (angle : float, min : float, max : float) {
    60.     if (angle < -360)
    61.         angle += 360;
    62.     if (angle > 360)
    63.         angle -= 360;
    64.     return Mathf.Clamp (angle, min, max);
    65. }

    It seems to be working alright but is there away to optimized these codes?


    ......
     
  3. pretender

    pretender

    Joined:
    Mar 6, 2010
    Posts:
    865
    sorry, i am a beginner i dont know how to use this.
    i was using default MouseOrbit but i dont understand how to use this one, when i attach it to empty GO i get some errors...can you explain how i should use this script.

    i am also searching for similiar camera code. it should be able to orbit freely around the selected target, just as you explained...help please.
     
  4. nntvog

    nntvog

    Joined:
    Nov 14, 2009
    Posts:
    6
    • Copy the codes above and make it a .js file (eg Mouseorbit.js)
    • Create an new empty object in Hierarchy panel
    • Drop and drag Mouseorbit.js to the new object.
    • Make sure you are selecting the object. In the Inspector panel, map the Target property to the target you want to follow and map the Camera property to the main Camera
     
  5. nntvog

    nntvog

    Joined:
    Nov 14, 2009
    Posts:
    6
    Or you can attached the below code to the main Camera. You only need to map the Target property to the object you want to follow. No additional empty object needed.

    Code (csharp):
    1.  
    2. var target : Transform;
    3. var distance = 10.0;
    4. var cameraSpeed = 5;
    5.  
    6. var xSpeed = 175.0;
    7. var ySpeed = 75.0;
    8.  
    9. var yMinLimit = 20; //Lowest vertical angle in respect with the target.
    10. var yMaxLimit = 80;
    11.  
    12. var minDistance = 5; //Min distance of the camera from the target
    13. var maxDistance = 20;
    14.  
    15. private var x = 0.0;
    16. private var y = 0.0;
    17.  
    18. function Start () {
    19.     var angles = transform.eulerAngles;
    20.     x = angles.y;
    21.     y = angles.x;
    22.  
    23.    // Make the rigid body not change rotation
    24.       if (rigidbody)
    25.       rigidbody.freezeRotation = true;
    26. }
    27.  
    28. function LateUpdate () {
    29.     if (target  camera) {
    30.  
    31.    //Zooming with mouse
    32.    distance += Input.GetAxis("Mouse ScrollWheel")*distance;
    33.    distance = Mathf.Clamp(distance, minDistance, maxDistance);
    34.  
    35.    //Detect mouse drag;
    36.    if(Input.GetMouseButton(0))   {
    37.    
    38.         x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
    39.         y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;      
    40.       }
    41.       y = ClampAngle(y, yMinLimit, yMaxLimit);
    42.              
    43.         var rotation = Quaternion.Euler(y, x, 0);
    44.         var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;
    45.          
    46.    transform.position = Vector3.Lerp (transform.position, position, cameraSpeed*Time.deltaTime);
    47.       transform.rotation = rotation;      
    48.     }
    49. }
    50.  
    51. static function ClampAngle (angle : float, min : float, max : float) {
    52.    if (angle < -360)
    53.       angle += 360;
    54.    if (angle > 360)
    55.       angle -= 360;
    56.    return Mathf.Clamp (angle, min, max);
    57. }
    58.  
     
  6. pretender

    pretender

    Joined:
    Mar 6, 2010
    Posts:
    865
    here is the error i got with this script:

    'eulerAngles' is not a member of 'UnityEngine.Camera'.
    'position' is not a member of 'UnityEngine.Camera'.

    and there is no option in the inspector to map the target object to the script

    am i doing something wrong? can somebody verify?
     
  7. nntvog

    nntvog

    Joined:
    Nov 14, 2009
    Posts:
    6
    Sorry I forgot update the code.
    All you need to do is find and change the "camera.eulerAngles" to "transform.eulerAngles" and "camera.position" to "transform.position"
    I have edited the code above.

    Drag this code (name it "orbit.js" for instance) to "Main Camera" object. then in the "Inspector" panel find the Script section and change the "Target" to the object you want to follow.


    Edit: I attached the js and some pic in case you are lost.
     

    Attached Files:

  8. pretender

    pretender

    Joined:
    Mar 6, 2010
    Posts:
    865
    great this works now, i will now play with it...
    thanks!
     
  9. asimov

    asimov

    Joined:
    Mar 14, 2012
    Posts:
    8
    Hi,

    I realise this thread is very old, but its worth a try.

    I am working in C# and have tried to convert the script, but am getting the following error in Unity:
    I have called the script ZoomTarget2, the error is is on line 55.
    The C# script is as follows - Any ideas?

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. //@script RequireComponent ("Camera-Control/Mouse Orbit")
    5.  
    6. public class ZoomTarget2 : MonoBehaviour {
    7.  
    8.     //This code should attached to an empty object
    9.     //I would name it "Camera Controller"
    10.     public Transform target;
    11.     public Transform camera; //In case you have more than one camera
    12.     public float distance = 10.0F;
    13.     public int cameraSpeed = 5;
    14.      
    15.     float xSpeed = 175.0F;
    16.     float ySpeed = 75.0F;
    17.      
    18.     int yMinLimit = 20; //Lowest vertical angle in respect with the target.
    19.     int yMaxLimit = 80;
    20.      
    21.     int minDistance = 5; //Min distance of the camera from the target
    22.     int maxDistance = 20;
    23.      
    24.     private float x = 0.0F;
    25.     private float y = 0.0F;
    26.      
    27.  
    28.      
    29.     void Start () {
    30.         var angles = transform.eulerAngles;
    31.         x = angles.y;
    32.         y = angles.x;
    33.      
    34.        // Make the rigid body not change rotation
    35.           if (rigidbody)
    36.           rigidbody.freezeRotation = true;
    37.     }
    38.      
    39.     void Update () {
    40.         if (target  camera) {
    41.      
    42.        //Zooming with mouse
    43.        distance += Input.GetAxis("Mouse ScrollWheel")*distance;
    44.        distance = Mathf.Clamp(distance, minDistance, maxDistance);
    45.      
    46.        //Detect mouse drag;
    47.        if(Input.GetMouseButton(0))   {
    48.        
    49.             x += Input.GetAxis("Mouse X") * xSpeed * 0.02F;
    50.             y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02F;      
    51.           }
    52.           y = ClampAngle(y, yMinLimit, yMaxLimit);
    53.                  
    54.             Quaternion rotation = Quaternion.Euler(y, x, 0);
    55.             Transform position = rotation * Vector3(0.0, 0.0, -distance) + target.position;
    56.              
    57.           transform.position = Vector3.Lerp (transform.position, position, cameraSpeed*Time.deltaTime);
    58.           transform.rotation = rotation;      
    59.         }
    60.     }
    61.      
    62.         static float ClampAngle (float angle, float min, float max) {
    63.          if (angle < -360)
    64.             angle += 360;
    65.          if (angle > 360)
    66.             angle -= 360;
    67.        
    68.         return Mathf.Clamp (angle, min, max);
    69.     }
    70. }
     
    stereoplanet likes this.
  10. Myx

    Myx

    Joined:
    Nov 29, 2010
    Posts:
    196
    Hello!

    If you add "new" before the Vector3 on line 55 your problems should resolve. Vector3 is as the error-message says a type, it's not an actual variable. By adding new before it you indicate that you want to create a variable of the vector3 type.
     
  11. cengizhangokben

    cengizhangokben

    Joined:
    Jul 3, 2012
    Posts:
    1
    use that for mouse scroolWheel

    Code (csharp):
    1. camera.fieldOfView += Input.GetAxis("Mouse ScrollWheel");
     
  12. Korpz

    Korpz

    Joined:
    May 20, 2013
    Posts:
    1
    Hey there
    I'm very new to unity and coding in general. Is there a way to adapt the c# script so that the target is an object clicked on at runtime or would this require a separate script?
    Any help greatly appreciated.
    Korpz
     
  13. lonetree

    lonetree

    Joined:
    Nov 30, 2012
    Posts:
    16
    this script works well except camera's target moves whenever i try to rotate.
    though camera target resets to original point. is there any way to fix target always?
     
    AnandKumarMS likes this.
  14. UnitedUFOs

    UnitedUFOs

    Joined:
    Sep 10, 2021
    Posts:
    1
    Here is a good script that are quite easy for beginners. Hold right mouse button to change camera angel and mouse scroll to change distance.

    Put script in camera object then in UNITY inspector for camera and script set target/player + camera + min and max values for distance to player.

    No need to set any object as child for this to work but player or target controlls have to be set on player/target with another script.

    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using System.Collections;
    4. public class MouseLook : MonoBehaviour
    5. {
    6.     public Transform target;
    7.     public Camera cameraObj;
    8.     public float minDistance;
    9.     public float maxDistance;
    10.     private float rotationSpeed = 2f;
    11.     private bool rightIsActivated;
    12.     private Vector3 offset;
    13.  
    14.     void Start ()
    15.     {
    16.         offset = transform.position - target.transform.position;
    17.         transform.LookAt(target);
    18.     }
    19.     void Update ()
    20.     {
    21.         if (Input.GetMouseButtonDown(1)){
    22.             rightIsActivated = true;
    23.         }
    24.         if (Input.GetMouseButtonUp(1))
    25.         {
    26.             rightIsActivated = false;
    27.         }
    28.      
    29.         if (rightIsActivated) {      
    30.             cameraObj.transform.RotateAround (target.transform.position, Vector3.up, Input.GetAxis("Mouse X")*rotationSpeed);
    31.             cameraObj.transform.RotateAround (target.transform.position, Vector3.right, -Input.GetAxis("Mouse Y")*rotationSpeed);
    32.             transform.LookAt(target);
    33.             offset = transform.position - target.transform.position;
    34.         }
    35.  
    36.         if (Input.GetAxis("Mouse ScrollWheel") != 0f) {
    37.             cameraObj.fieldOfView -= 8 * Input.GetAxis("Mouse ScrollWheel");
    38.             cameraObj.fieldOfView = Mathf.Clamp(cameraObj.fieldOfView, minDistance, maxDistance);
    39.         }
    40.     }
    41.  
    42.     void LateUpdate ()
    43.     {
    44.         if (!rightIsActivated)
    45.         transform.position = target.transform.position + offset;
    46.     }
    47. }            
    48.  
     
    Last edited: Oct 4, 2021
  15. anchalin7

    anchalin7

    Joined:
    Jul 23, 2019
    Posts:
    3
    public class CameraModel : MonoBehaviour
    {
    //This code should attached to an empty object
    //I would name it "Camera Controller"
    public Transform target;
    public Transform camera; //In case you have more than one camera
    public float distance = 10.0F;
    public int cameraSpeed = 5;

    float xSpeed = 175.0F;
    float ySpeed = 75.0F;

    int yMinLimit = 20; //Lowest vertical angle in respect with the target.
    int yMaxLimit = 80;

    int minDistance = 5; //Min distance of the camera from the target
    int maxDistance = 20;

    private float x = 0.0F;
    private float y = 0.0F;



    void Start()
    {
    var angles = transform.eulerAngles;
    x = angles.y;
    y = angles.x;

    }
    void Update()
    {
    if (target)
    {
    //Zooming with mouse
    distance += Input.GetAxis("Mouse ScrollWheel") * distance;
    distance = Mathf.Clamp(distance, minDistance, maxDistance);

    //Detect mouse drag;
    if (Input.GetMouseButton(0))
    {

    x += Input.GetAxis("Mouse X") * xSpeed * 0.02F;
    y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02F;
    }
    y = ClampAngle(y, yMinLimit, yMaxLimit);

    Quaternion rotation = Quaternion.Euler(y, x, 0);
    Vector3 position = rotation * new Vector3(0.0f, 0.0f, distance) + target.position;

    transform.position = Vector3.Lerp(transform.position, position, cameraSpeed * Time.deltaTime);
    transform.rotation = rotation;
    }
    }

    static float ClampAngle(float angle, float min, float max)
    {
    if (angle < -360)
    angle += 360;
    if (angle > 360)
    angle -= 360;

    return Mathf.Clamp(angle, min, max);
    }
    }
    This is nice one bro.. Good work