Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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?
     
  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. }
     
  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.
     
    tacosauce1337 likes this.
  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:
    79
    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:
    16
    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:
    9
    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!
     
    kamaldeep26594 likes this.
  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:
    199
    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:
    13
    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:
    3
    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
  24. RKar

    RKar

    Joined:
    Mar 6, 2019
    Posts:
    22
    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. d4rkdr460n

    d4rkdr460n

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

    SuperCrow2

    Joined:
    Mar 8, 2018
    Posts:
    584
    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.
     
  27. d4rkdr460n

    d4rkdr460n

    Joined:
    Feb 27, 2014
    Posts:
    4
    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
     
  28. SuperCrow2

    SuperCrow2

    Joined:
    Mar 8, 2018
    Posts:
    584
    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?
     
  29. d4rkdr460n

    d4rkdr460n

    Joined:
    Feb 27, 2014
    Posts:
    4
    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/
     
  30. SuperCrow2

    SuperCrow2

    Joined:
    Mar 8, 2018
    Posts:
    584
    Thanks.

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

    d4rkdr460n

    Joined:
    Feb 27, 2014
    Posts:
    4
    I don't know of any tutorials but I would do something like this:
    Code (CSharp):
    1.  
    2. //When you register a mouse click convert it to world position and save it
    3. Vector3 clickpos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    4. // then use that point as a target for lerping the cam with
    5. Camera.main.transform.position = Vector3.Lerp(Camera.main.transform.position , clickpos , 0.3f);
    6.  
     
  32. SuperCrow2

    SuperCrow2

    Joined:
    Mar 8, 2018
    Posts:
    584
    it worked, thanks!

    I have it in a "void Update()" function, that seems to work fine, but do you think it should be in a void "OnMouseDown()"
    function instead?
     
  33. Galaxyben

    Galaxyben

    Joined:
    Jul 19, 2017
    Posts:
    5
    Hey! I want to know to make Click+drag camera movement but mixed with cinemachine :( It would be of much help

    Edit: Plus moving front and backwards from camera's perspective
     
  34. corriedotdev

    corriedotdev

    Joined:
    Sep 1, 2012
    Posts:
    21
    Working on it.
     
  35. sajjadgameactor

    sajjadgameactor

    Joined:
    May 27, 2015
    Posts:
    8
    I write a simple and reliable script for my game to handle camera drag and swipe for any aspect ratio. Everyone can use this code easily :)

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3.     public class CameraDragController : MonoBehaviour
    4.     {
    5.         [SerializeField] private Vector2 xBoundWorld;
    6.         [SerializeField] private Vector2 yBoundWorld;
    7.         [SerializeField] public bool HorizentalDrag = true;
    8.         [SerializeField] public bool VerticalDrag = true;
    9.         [SerializeField] public float speedFactor = 10;
    10.  
    11.         private float leftLimit;
    12.         private float rightLimit;
    13.         private float topLimit;
    14.         private float downLimit;
    15.  
    16.         public bool allowDrag = true;
    17.         private void Start()
    18.         {
    19.             CalculateLimitsBasedOnAspectRatio();
    20.         }
    21.  
    22.         public void UpdateBounds(Vector2 xBoundNew, Vector2 yBoundNew)
    23.         {
    24.             xBoundWorld = xBoundNew;
    25.             yBoundWorld = yBoundNew;
    26.             CalculateLimitsBasedOnAspectRatio();
    27.         }
    28.  
    29.         private void CalculateLimitsBasedOnAspectRatio()
    30.         {
    31.             leftLimit = xBoundWorld.x - Camera.main.ViewportToWorldPoint(new Vector3(0, 0, 0)).x;
    32.             rightLimit = xBoundWorld.y - Camera.main.ViewportToWorldPoint(new Vector3(1, 0, 0)).x;
    33.             downLimit = yBoundWorld.x - Camera.main.ViewportToWorldPoint(new Vector3(0, 0, 0)).y;
    34.             topLimit = yBoundWorld.y - Camera.main.ViewportToWorldPoint(new Vector3(0, 1, 0)).y;
    35.         }
    36.  
    37.         Vector3 lastPosView; // we use viewport because we don't want devices pixel density affect our swipe speed
    38.         private void LateUpdate()
    39.         {
    40.             if (allowDrag)
    41.             {
    42.                 if (Input.GetMouseButtonDown(0))
    43.                 {
    44.                     lastPosView = Camera.main.ScreenToViewportPoint(Input.mousePosition);
    45.                 }
    46.                 else if (Input.GetMouseButton(0))
    47.                 {
    48.                     var newPosView = Camera.main.ScreenToViewportPoint(Input.mousePosition);
    49.                     var cameraMovment = (lastPosView - newPosView) * speedFactor;
    50.                     lastPosView = newPosView;
    51.  
    52.                     cameraMovment = Limit2Bound(cameraMovment);
    53.  
    54.                     if (HorizentalDrag)
    55.                         Camera.main.transform.Translate(new Vector3(cameraMovment.x, 0, 0));
    56.                     if (VerticalDrag)
    57.                         Camera.main.transform.Translate(new Vector3(0, cameraMovment.y, 0));
    58.                 }
    59.             }
    60.         }
    61.  
    62.         private Vector3 Limit2Bound(Vector3 distanceView)
    63.         {
    64.             if (distanceView.x < 0) // Check left limit
    65.             {
    66.                 if (Camera.main.transform.position.x + distanceView.x < leftLimit)
    67.                 {
    68.                     distanceView.x = leftLimit - Camera.main.transform.position.x;
    69.                 }
    70.             }
    71.             else // Check right limit
    72.             {
    73.                 if (Camera.main.transform.position.x + distanceView.x > rightLimit)
    74.                 {
    75.                     distanceView.x = rightLimit - Camera.main.transform.position.x;
    76.                 }
    77.             }
    78.  
    79.             if (distanceView.y < 0) // Check down limit
    80.             {
    81.                 if (Camera.main.transform.position.y + distanceView.y < downLimit)
    82.                 {
    83.                     distanceView.y = downLimit - Camera.main.transform.position.y;
    84.                 }
    85.             }
    86.             else // Check top limit
    87.             {
    88.                 if (Camera.main.transform.position.y + distanceView.y > topLimit)
    89.                 {
    90.                     distanceView.y = topLimit - Camera.main.transform.position.y;
    91.                 }
    92.             }
    93.  
    94.             return distanceView;
    95.         }
    96.     }
     
  36. Gone2Plaid

    Gone2Plaid

    Joined:
    Jan 18, 2020
    Posts:
    3
    I have a map with a top-down view and the ability to zoom in and out. I had issues with several click and pan scripts that I found in that they would cause the map to keep moving until I released the mouse or they would quickly disappear off the screen and couldn't get them back (that's what happened with sajjadgameactor's script above). Here's what I ended up with that worked for me. See the items I marked as needing to tweak. Recommendations on how to get the right values without trial and error - maybe based on other camera parameters? - would be welcomed.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class CameraPanControl : MonoBehaviour
    4. {
    5.     // Original code sourced from LostConjugate & Matti Jokihaara via
    6.     // https://www.youtube.com/watch?v=mJCbEL5J5fg
    7.  
    8.     float dragSpeed = 15f; // Found this by trial and error - applied below in Update
    9.  
    10.     float scale;
    11.     float normalizedScale = 250f; // Found this by trial and error - applied below in Update
    12.  
    13.     void Update()
    14.     {
    15.         Vector3 pos = transform.position;
    16.  
    17.         scale = Camera.main.orthographicSize;  // Use this to capture the zoom level
    18.  
    19.         if (Input.GetMouseButton(0))
    20.         {
    21.             pos.x -= Input.GetAxis("Mouse X") * dragSpeed * scale / normalizedScale;
    22.             pos.z -= Input.GetAxis("Mouse Y") * dragSpeed * scale / normalizedScale;
    23.         }
    24.  
    25.         transform.position = pos;
    26.     }
    27. }
     
  37. robal1991

    robal1991

    Joined:
    Mar 31, 2016
    Posts:
    33
    The solution above is ok, but it is not ideal. If I move the mouse quickly while panning the camera, then the camera "stays" behind, that means that the mouse vector that I moved is much longer that the camera movement vector. I would like it to be "glued" -> the mouse move vector should be equal to the camera move vector (no matter what the orthogonal camera size is or what screen size/aspect ratio is).

    Do you guys have a solution to that? It seems to me that using Input.GetAxis is the bottleneck here.
     
  38. RKar

    RKar

    Joined:
    Mar 6, 2019
    Posts:
    22
    Something like this?

    Code (CSharp):
    1. if (Input.GetKey(moveKey) && canMove)
    2.             {       //raycast to Plane(Vector3.up, new Vector3(0, 0, 0));
    3.                 if (GetGroundPosition(MousePosition, out Vector3 groundPos))
    4.                 {
    5.                     Vector3 deltaPos = (startMovingPos - groundPos) * lerpScale;
    6.  
    7.                     if (Mathf.Abs(deltaPos.x) > movingMinDelta || Mathf.Abs(deltaPos.y) > movingMinDelta)
    8.                     {
    9.                         mousePhase = MousePhase.Moving;
    10.  
    11.                         Vector3 newPos = cameraTransform.position + deltaPos;
    12.  
    13.                         cameraTransform.position = LimitPosition(newPos);
    14.                     }
    15.                     else
    16.                     {
    17.                         mousePhase = MousePhase.Stacionary;
    18.                     }
    19.                 }
    20.             }
     
  39. robal1991

    robal1991

    Joined:
    Mar 31, 2016
    Posts:
    33
    Could you should me entire code? What does GetGroundPosition and LimitPosition look like?
     
  40. RKar

    RKar

    Joined:
    Mar 6, 2019
    Posts:
    22
    I can't show everything. LimitPosition - limiting camera movement. GetGroundPosition - just mouse-to-plane raycast
     
  41. robal1991

    robal1991

    Joined:
    Mar 31, 2016
    Posts:
    33
    Ok cool. Thanks for trying to help.

    I'm still fighting with this. The camera move is for sure related to the orthographic camera size, screen size and camera viewport. Input.GetAxis("Mouse X/Y") is inaccurate and behaves differently on different platforms (Editor, WebGL, UWP). I want an universal solution when I can pan the camera with right mouse button and I want the camera to be glued to the cursor when panning (the move vector should be exactly the same).
     
    Last edited: Apr 1, 2021
  42. 0rd0

    0rd0

    Joined:
    Feb 3, 2014
    Posts:
    2
    frixou89 likes this.
  43. PeterGost

    PeterGost

    Joined:
    Jan 27, 2020
    Posts:
    18
    @cjgstudio Any good ideas?
     
  44. VincentLogus

    VincentLogus

    Joined:
    Jun 6, 2020
    Posts:
    1
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class DragCamera : MonoBehaviour
    {
    private Vector3 ResetCamera;
    private Vector3 Origin;
    private Vector3 Diference;
    private bool Drag = false;
    public Vector3 borderLeft;//x-
    public Vector3 borderRight;//x+
    public Vector3 borderUp;//y+
    public Vector3 borderDown;//y-
    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;
    if (Camera.main.transform.position.x> borderRight.x)
    {
    Camera.main.transform.position= new Vector3(borderRight.x, Origin.y - Diference.y, Camera.main.transform.position.z); ;
    Debug.Log("right");
    }
    if (Camera.main.transform.position.x < borderLeft.x)
    {
    Camera.main.transform.position = new Vector3(borderLeft.x, Origin.y - Diference.y, Camera.main.transform.position.z); ;
    Debug.Log("left");
    }
    if (Camera.main.transform.position.y > borderUp.y)
    {
    Camera.main.transform.position = new Vector3(Origin.x - Diference.x, borderUp.y, Camera.main.transform.position.z); ;
    Debug.Log("up");
    }
    if (Camera.main.transform.position.y < borderDown.y)//riddle for you
    {
    Camera.main.transform.position = new Vector3(Origin.x - Diference.x, borderDown.y, Camera.main.transform.position.z); ;
    Debug.Log("low");
    if (Camera.main.transform.position.x < borderLeft.x)
    {
    Camera.main.transform.position = new Vector3(borderLeft.x, borderDown.y, Camera.main.transform.position.z); ;
    Debug.Log("Leftdown");
    }
    if (Camera.main.transform.position.x > borderRight.x)
    {
    Camera.main.transform.position = new Vector3(borderRight.x, borderDown.y, Camera.main.transform.position.z); ;
    Debug.Log("rightdown");
    }
    }

    if (Camera.main.transform.position.x < borderLeft.x || Camera.main.transform.position.y > borderUp.y)
    {
    Camera.main.transform.position = new Vector3(borderLeft.x, borderUp.y, Camera.main.transform.position.z); ;
    Debug.Log("leftup");
    }
    if (Camera.main.transform.position.x > borderRight.x || Camera.main.transform.position.y > borderUp.y)
    {
    Camera.main.transform.position = new Vector3(borderRight.x, borderUp.y, Camera.main.transform.position.z); ;
    Debug.Log("rightup");
    }
    }
    //RESET CAMERA TO STARTING POSITION WITH RIGHT CLICK
    if (Input.GetMouseButton(1))
    {
    Camera.main.transform.position = ResetCamera;
    }
    }
    }

    //I've been working on this and this what I have the solution for the border
    //only thing you need to do is put this script into the camera and adjust the vector3 in inspecter
    //you need to set each up/down/left/right border that your camera can move
    upload_2022-1-21_19-55-36.png
    //like this
    //so for this setting you can't move more than -50 to left / 50 to right / 50 to up /-50 to down just like that
    //if you look closely at "riddle for you" of my code
    //plese answer below "why did I check position.x inside position.y" XD anyway .. goodluck
    //by the way this is the way to move your camera in 2D NOT IN 3D
    //if any one have question in moving camera in 3D serch out "Raycast" option
     
  45. Rachan

    Rachan

    Joined:
    Dec 3, 2012
    Posts:
    759
    Thanks you very much!
    it work!!!
     
  46. DirtyFred

    DirtyFred

    Joined:
    May 17, 2014
    Posts:
    29
    Thank you!