Search Unity

How to lock panning camera movement to the Y axis?

Discussion in '2D' started by Kenthria11, Sep 28, 2019.

  1. Kenthria11

    Kenthria11

    Joined:
    May 6, 2017
    Posts:
    20
    Hi, I have an environment for mobile devices that needs to allow players to scroll up and down - with an upper and lower limit.

    The only script I have found allows for free movement - panning in every direction.

    Could someone please help me out with this? Thanks a lot.

    To clarify - I need a new script, or my current script, to allow players to touch move the camera along the Y axis only, but an upper and lower limit.

    Current code:
    Code (CSharp):
    1. Vector3 touchStart;
    2.  
    3.     void Update()
    4.     {
    5.         if (Input.GetMouseButtonDown(0))
    6.         {
    7.             touchStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    8.         }
    9.  
    10.        if (Input.GetMouseButton(0))
    11.         {
    12.             Vector3 direction = touchStart - Camera.main.ScreenToWorldPoint(Input.mousePosition);
    13.             Camera.main.transform.position += direction;
    14.         }
    15.     }
     
  2. Kenthria11

    Kenthria11

    Joined:
    May 6, 2017
    Posts:
    20
    Got help elsewhere - this code does the job!

    Code (CSharp):
    1.     Vector3 touchStart;
    2.     public int upperLimit = 0;
    3.     public int lowerLimit = 7000;
    4.  
    5.     void Update()
    6.     {
    7.         if (Input.GetMouseButtonDown(0))
    8.         {
    9.             touchStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    10.         }
    11.  
    12.         if (Input.GetMouseButton(0))
    13.         {
    14.             Vector3 direction = touchStart - Camera.main.ScreenToWorldPoint(Input.mousePosition);
    15.             float finalYPos = Camera.main.transform.position.y + direction.y;
    16.             finalYPos = Mathf.Clamp(finalYPos, lowerLimit, upperLimit);
    17.             Camera.main.transform.position = new Vector3(Camera.main.transform.position.x, finalYPos, Camera.main.transform.position.z);
    18.             Debug.Log(finalYPos);
    19.         }
    20.     }
     
    CptTrihulka and mmcar like this.