Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make the border of a map and the panning of that map the same?

Tags:

unity3d

I am using a map bigger than the screen I viewing. Therefore I need to be able to pan around that map. I am having a problem with clamping the camera and the map. I want to be able to use the demension of the image as the width and height of the clamp. The problem is the units.

The image is 2144 x 1708 The camera transposition is in single digits (14 x 7) or something like that.

All of the code I am using is below.

private Vector3 mouseOrigin;    // Position of cursor when mouse dragging starts
private bool isPanning;         // Is the camera being panned?

public bool useBoundary = true;
public Vector2 boundaryMin;
public Vector2 boundaryMax;
public Image map;

private void Start()
{
    Camera cam     = Camera.main;
    float mapRatio = map.rectTransform.rect.width / map.rectTransform.rect.height;

    float mapScreenHeight = (1.5f * cam.orthographicSize);
    float mapScreenWidth  = (3f * mapScreenHeight) * cam.aspect;

    boundaryMin = new Vector2(0, 1);
    boundaryMax = new Vector2(map.rectTransform.rect.width, map.rectTransform.rect.height);
}
private void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        mouseOrigin = Input.mousePosition;
        isPanning   = true;
    }
    // Disable movements on button release
    if (!Input.GetMouseButton(0)) 
        isPanning = false;
    if (isPanning)
    {
        Vector3 pos  = Camera.main.ScreenToViewportPoint(Input.mousePosition - mouseOrigin);
        Vector3 move = new Vector3(pos.x * panSpeed, pos.y * panSpeed, 0);
        transform.Translate(move, Space.Self);
        BoundaryCheck();
    }
}
private void BoundaryCheck()
{
    if (!useBoundary)
        return;
    Vector3 newPos = transform.position;

    newPos.x = Mathf.Clamp(newPos.x, boundaryMin.x, boundaryMax.x);
    newPos.y = Mathf.Clamp(newPos.y, boundaryMin.y, boundaryMax.y);
    transform.position = newPos;
}

}

Any help would be greatly appreciated.

like image 247
Tim Cooley Avatar asked Sep 21 '16 00:09

Tim Cooley


1 Answers

You can do this using Unity UI - Scroll Rect.

Check out Unity UI - Scroll Rect - Introduction

like image 80
Anmol Mahatpurkar Avatar answered Oct 21 '22 22:10

Anmol Mahatpurkar