Search Unity

Click+drag camera movement

Discussion in 'Scripting' started by roBurky_legacy, Jan 21, 2010.

  1. roBurky_legacy

    roBurky_legacy

    Joined:
    Nov 7, 2009
    Posts:
    17
    Hello,

    We're making a board game-style turn-based game in Unity, and I would like to have a system where you click and drag on the board to move the camera. Like you're grabbing hold of the board with the mouse.

    I am a little at a loss as to how to begin to code something like this, however. Particularly with the camera positioned at an angle, rather than viewing directly top-down.

    Can anyone offer any suggestions?
     
    riagrawal, Aloestylez and salihkallai like this.
  2. damien_oconnell

    damien_oconnell

    Joined:
    Dec 24, 2009
    Posts:
    58
    This should get you started:

    Code (csharp):
    1. using UnityEngine;
    2.  
    3. public class CameraDrag : MonoBehaviour
    4. {
    5.     public float dragSpeed = 2;
    6.     private Vector3 dragOrigin;
    7.  
    8.  
    9.     void Update()
    10.     {
    11.         if (Input.GetMouseButtonDown(0))
    12.         {
    13.             dragOrigin = Input.mousePosition;
    14.             return;
    15.         }
    16.  
    17.         if (!Input.GetMouseButton(0)) return;
    18.  
    19.         Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - dragOrigin);
    20.         Vector3 move = new Vector3(pos.x * dragSpeed, 0, pos.y * dragSpeed);
    21.  
    22.         transform.Translate(move, Space.World);  
    23.     }
    24.  
    25.  
    26. }
     
    PacinoPxn, synthc, FreekV and 9 others like this.
  3. roBurky_legacy

    roBurky_legacy

    Joined:
    Nov 7, 2009
    Posts:
    17
    Thanks. That has indeed got me started.
     
  4. Hasneet Dhalor

    Hasneet Dhalor

    Joined:
    Jul 25, 2014
    Posts:
    1
    The script works pretty well.

    Now, how to restrict the co-ordinates. Like i want to restrict its movement on x-axis only i.e. (0,0,0) to (10,0,0)
    :)
     
  5. DeltaM

    DeltaM

    Joined:
    Sep 2, 2014
    Posts:
    1
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class DragCamera : MonoBehaviour
    5. {
    6.     public float dragSpeed = 2;
    7.     private Vector3 dragOrigin;
    8.    
    9.     public bool cameraDragging = true;
    10.    
    11.     public float outerLeft = -10f;
    12.     public float outerRight = 10f;
    13.  
    14.    
    15.     void Update()
    16.     {
    17.        
    18.  
    19.            
    20.         Vector2 mousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
    21.        
    22.         float left = Screen.width * 0.2f;
    23.         float right = Screen.width - (Screen.width * 0.2f);
    24.        
    25.         if(mousePosition.x < left)
    26.         {
    27.             cameraDragging = true;
    28.         }
    29.         else if(mousePosition.x > right)
    30.         {
    31.             cameraDragging = true;
    32.         }
    33.            
    34.  
    35.        
    36.        
    37.        
    38.        
    39.         if (cameraDragging) {
    40.            
    41.             if (Input.GetMouseButtonDown(0))
    42.             {
    43.                 dragOrigin = Input.mousePosition;
    44.                 return;
    45.             }
    46.            
    47.             if (!Input.GetMouseButton(0)) return;
    48.            
    49.             Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - dragOrigin);
    50.             Vector3 move = new Vector3(pos.x * dragSpeed, 0, 0);
    51.            
    52.             if (move.x > 0f)
    53.             {
    54.                 if(this.transform.position.x < outerRight)
    55.                 {
    56.                     transform.Translate(move, Space.World);
    57.                 }
    58.             }
    59.             else{
    60.                 if(this.transform.position.x > outerLeft)
    61.                 {
    62.                     transform.Translate(move, Space.World);
    63.                 }
    64.             }
    65.         }
    66.     }
    67.    
    68.    
    69. }
     
  6. ethanguo

    ethanguo

    Joined:
    Oct 26, 2014
    Posts:
    1
    Just a comment, camera code should go in LateUpdate().

    EDIT: Sorry for the necro, someone else necro'd it and I only looked at the last post.
     
  7. Franco-Marini

    Franco-Marini

    Joined:
    Apr 2, 2014
    Posts:
    2
    Sorry if im late. Here you have the script.
    public class CameraDragMove : MonoBehaviour {
    private Vector3 ResetCamera;
    private Vector3 Origin;
    private Vector3 Diference;
    private bool Drag=false;
    void Start () {
    ResetCamera = Camera.main.transform.position;
    }
    void LateUpdate () {
    if (Input.GetMouseButton (0)) {
    Diference=(Camera.main.ScreenToWorldPoint (Input.mousePosition))- Camera.main.transform.position;
    if (Drag==false){
    Drag=true;
    Origin=Camera.main.ScreenToWorldPoint (Input.mousePosition);
    }
    } else {
    Drag=false;
    }
    if (Drag==true){
    Camera.main.transform.position = Origin-Diference;
    }
    //RESET CAMERA TO STARTING POSITION WITH RIGHT CLICK
    if (Input.GetMouseButton (1)) {
    Camera.main.transform.position=ResetCamera;
    }
    }
    }
     
  8. artistshc

    artistshc

    Joined:
    Mar 7, 2015
    Posts:
    70
    This helped me immensely. Great code!
     
    Last edited: Nov 11, 2015
  9. natanacs25

    natanacs25

    Joined:
    Nov 17, 2015
    Posts:
    1
    DeltaM, very good guy your script, but the mouse drag it passes the threshold, how to solve this?
     
  10. mauramo33

    mauramo33

    Joined:
    Jun 24, 2015
    Posts:
    1
    if u put the control for the Y axis u save my life :) pls! :D
     
  11. dead_byte_dawn

    dead_byte_dawn

    Joined:
    May 7, 2015
    Posts:
    9
    This helped a lot thanks! How would I clamp movement? Let's say I wanted to restrict movement to Horizontal panning only? Kind of like Neko Atsume?
     
  12. rus89

    rus89

    Joined:
    Apr 22, 2015
    Posts:
    6
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. [RequireComponent(typeof(BoxCollider2D))]
    6. public class CameraBounds : MonoBehaviour
    7. {
    8.     public Camera linkedCamera;
    9.     private BoxCollider2D boxCollider;
    10.  
    11.     private void Start()
    12.     {
    13.         boxCollider = this.GetComponent<BoxCollider2D>();
    14.     }
    15.  
    16.     private void LateUpdate()
    17.     {
    18.         float vertExtent = linkedCamera.orthographicSize;
    19.         float horizExtent = vertExtent * Screen.width / Screen.height;
    20.  
    21.         Vector3 linkedCameraPos = linkedCamera.transform.position;
    22.         Bounds areaBounds = boxCollider.bounds;
    23.  
    24.         linkedCamera.transform.position = new Vector3(
    25.             Mathf.Clamp(linkedCameraPos.x, areaBounds.min.x + horizExtent, areaBounds.max.x - horizExtent),
    26.             Mathf.Clamp(linkedCameraPos.y, areaBounds.min.y + vertExtent, areaBounds.max.y - vertExtent),
    27.             linkedCameraPos.z);
    28.     }
    29. }
    30.  
    I found some code for clamp the movement of camera. Attach this script to GameObject you would like to use as bounds, and set the size of BoxCollider2D. I hope this will help you.

    Be great :)
     
    Aurhan, dead_byte_dawn and Orrib like this.
  13. drninja

    drninja

    Joined:
    Apr 13, 2017
    Posts:
    5
    This is an excellent script for camera movement! Just wondering though if anyone has any suggestions for how to pan the camera only while the mouse is moving. In the above scripts while the right mouse button is held down and the mouse is moved from it's starting position the camera will continue to pan until the right mouse button is let go. What if I only wanted the camera to pan whilst I dragged the mouse and then stop when I stop moving the mouse?

    Hope that makes sense!
     
  14. akpriest

    akpriest

    Joined:
    Jul 20, 2016
    Posts:
    5

    Your the man :D This worked perfect
     
  15. Alex_Bermann

    Alex_Bermann

    Joined:
    Feb 5, 2015
    Posts:
    6
    This work just great, but what if you want to move the camera in the x and y position? (Right now it moves in the horizontal (X) and "depth" ("Z", I think) axis. Thanks!
     
  16. MisaelGaray

    MisaelGaray

    Joined:
    Dec 17, 2015
    Posts:
    1
    It has a perfect panning
     
  17. UnaSim

    UnaSim

    Joined:
    Jun 9, 2016
    Posts:
    1
    This has been really helpful thank you guys so much,
    just wondering how i could then invert the direction the camera moved, so drag to the left would move it to the right?
     
  18. BrokawBound

    BrokawBound

    Joined:
    Dec 17, 2016
    Posts:
    6
    Simple solution to both invert movement and only move the camera while dragging at a consistent rate in a 3d world. This assumes the camera is facing the XZ plane at any angle and your dragging along the XZ plane. Easy enough to modify for any plane though.

    Code (CSharp):
    1.     public int cameraDragSpeed = 50;
    2.  
    3.     private void Update()
    4.     {
    5.         if (Input.GetMouseButton(1))
    6.         {
    7.             float speed = cameraDragSpeed * Time.deltaTime;
    8.             Camera.main.transform.position -= new Vector3(Input.GetAxis("Mouse X") * speed, 0, Input.GetAxis("Mouse Y") * speed);
    9.         }
    10.     }
     
  19. Rafarel

    Rafarel

    Joined:
    Jul 21, 2017
    Posts:
    165
    Thanks a lot to all of you guys that helped me get started with my Camera behavior ! Have a nice day :)
     
  20. dpelixir2

    dpelixir2

    Joined:
    Sep 6, 2018
    Posts:
    1
    sorry to ask i need camera should control with mouse click
     
  21. swebre2340

    swebre2340

    Joined:
    Oct 7, 2018
    Posts:
    1
    I need it to rotate around the player on a 3D plane, how would i get it to do this when dragging the mouse, and the player is also moving too
     
  22. gamesjust007

    gamesjust007

    Joined:
    Jan 3, 2017
    Posts:
    9
    Hi guys I see some beautiful code written by some beautiful and helpful people here.
    So i just wanted another thing added. I have played many games in which user can drag the camera around an object lets say a car which is usually termed as free camera in the games. I have tried almost everything but am unable to make that script. The script I make either starts rotating the camera when I am using UI buttons or sometimes behaves strangely... Can anyone please help me in this regard?
    If you want to have a demo, here is the video:


    from 3:20 onward the video maker uses free camera.

    Any help will highly be appreciated.
     
  23. Georges_d

    Georges_d

    Joined:
    Dec 17, 2018
    Posts:
    2
    I found this post trying to create a click and drag script for 2D project, here's the script for the camera:

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class ClickAndDrag : MonoBehaviour
    5. {
    6.     Vector2 mouseClickPos;
    7.     Vector2 mouseCurrentPos;
    8.     bool panning = false;
    9.  
    10.     private void Update()
    11.     {
    12.         // When LMB clicked get mouse click position and set panning to true
    13.         if (Input.GetKeyDown(KeyCode.Mouse0) && !panning)
    14.         {
    15.             mouseClickPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    16.             panning = true;
    17.         }
    18.         // If LMB is already clicked, move the camera following the mouse position update
    19.         if (panning)
    20.         {
    21.             mouseCurrentPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    22.             var distance = mouseCurrentPos - mouseClickPos;
    23.             transform.position += new Vector3(-distance.x,-distance.y,0);
    24.         }
    25.  
    26.         // If LMB is released, stop moving the camera
    27.         if (Input.GetKeyUp(KeyCode.Mouse0))
    28.             panning = false;
    29.     }
    30. }
    31.  
     
    Last edited: May 21, 2019
    Irgi and gamesjust007 like this.
  24. karimov995

    karimov995

    Joined:
    Mar 6, 2019
    Posts:
    2
    Just with out planning

    Code (CSharp):
    1. Vector2 mouseClickPos;
    2.     Vector2 mouseCurrentPos;
    3.  
    4.     private void Update()
    5.     {
    6.         // When LMB clicked get mouse click position and set panning to true
    7.         if (Input.GetKey(KeyCode.Mouse2))
    8.         {
    9.             if (mouseClickPos == default)
    10.             {
    11.                 mouseClickPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    12.             }
    13.  
    14.             mouseCurrentPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    15.             var distance = mouseCurrentPos - mouseClickPos;
    16.             transform.position += new Vector3(-distance.x, -distance.y, 0);
    17.         }
    18.  
    19.         // If LMB is released, stop moving the camera
    20.         if (Input.GetKeyUp(KeyCode.Mouse2))
    21.             mouseClickPos = default;
    22.     }
     
  25. AndrewHerrera1998Gamer

    AndrewHerrera1998Gamer

    Joined:
    Apr 20, 2019
    Posts:
    2
    A really short one off the top of my head:
    1. if (Input.GetMouseButton(1))
    2. {
    3. Camera.main.transform.position -= new Vector3(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"), 0)
    4. }
     
  26. d4rkdr460n

    d4rkdr460n

    Joined:
    Feb 27, 2014
    Posts:
    3
    If this is for a 2D game then the free asset Drag Camera 2D should do the trick. No point reinventing the wheel.
     
  27. SuperCrow2

    SuperCrow2

    Joined:
    Mar 8, 2018
    Posts:
    297
    I wasted my money so no one else have to.

    I got it, the free and pro version, wont let me download it. its no where in my Unity project.

    What a rip-off.
     
  28. d4rkdr460n

    d4rkdr460n

    Joined:
    Feb 27, 2014
    Posts:
    3
    Hi SuperCrow2,
    I just tried to make a new project with the free version and it worked first time with no issues. Maybe you should make a support ticket with the asset store to see if you can get the issue sorted out.
    dragcamtest.png
     
  29. SuperCrow2

    SuperCrow2

    Joined:
    Mar 8, 2018
    Posts:
    297
    I finally got it downloaded.

    Can you explain in simplest terms how to use it? In order for me to attach the srcipts to my camera was I had to make a new script outside of the editor folder. But for some reason, the "DragCamera2D" script I still couldnt attach because it didnt have "monobehavior" or whatever.

    Also, does this allow me to click once to move too instead of having to hold down the mouse button all the time?
     
  30. d4rkdr460n

    d4rkdr460n

    Joined:
    Feb 27, 2014
    Posts:
    3
    There should be a prefab camera already setup that you can just drop into you're hierarchy. I don't think it has the move to click thing though, its more of an RTS grab n drag type movement. Theres a couple of videos for an older version on this site https://www.gamedevelopment.blog/drag-camera-2d-pro-v1-2/
     
  31. SuperCrow2

    SuperCrow2

    Joined:
    Mar 8, 2018
    Posts:
    297
    Thanks.

    Do you know of any tutorials where there is click to move the screen? I cant seem to find any.
     
unityunity