0

Here is what I tried.

 public void OnDrag(PointerEventData eventData)
{
    float x;
    float y;
    rectTransform.anchoredPosition += eventData.delta;
   if (Background.transform.position.x >= xMaxBounds)
    {
        x = xMaxBounds;
    }
    else if (Background.transform.position.x < xMinBounds)
    {
        x = xMinBounds;
    }
    else
    {
        x=rectTransform.position.x;
    }

    if (Background.transform.position.y > yMaxBounds)
    {
        y = yMaxBounds;
    }
    else if (Background.transform.position.y < yMinBounds)
    {
        y = yMinBounds;
    }
    else
    {
        y = rectTransform.position.y;
    }
    rectTransform.position = new Vector3(x, y, rectTransform.position.z);
    
}

it locks the screen. I know that below works but allows me to drag the object off the screen. I want to clamp it so it cannot move off the side of the screens. This is like a virtual tabletop looking top down onto it and I don't want to lose that table object off the screen.

public void OnDrag(PointerEventData eventData)
{
    rectTransform.anchoredPosition += eventData.delta;
}

Any help is very appreciated I been stuck on this code for the last week trying all kinds of peoples suggestions I've found online but no problem I found was exactly like mine. So it was time to ask my question exactly since other similar solutions didn't help me.

kodarr
  • 1
  • 2

1 Answers1

0

Ok after lots of browsing and some tinkering I got this working

    public void OnDrag(PointerEventData eventData)
{
    float DragXPosition = (rectTransform.anchoredPosition.x + eventData.delta.x) / canvas.scaleFactor;
    float DragYPosition = (rectTransform.anchoredPosition.y + eventData.delta.y) / canvas.scaleFactor;

    if (DragXPosition <= xMinBounds)
    {
        DragXPosition = xMinBounds;
    }

    if (DragXPosition >= xMaxBounds)
    {
        DragXPosition = xMaxBounds;
    }

    if (DragYPosition <= yMinBounds)
    {
        DragYPosition = yMinBounds;
    }

    if (DragYPosition >= yMaxBounds)
    {
        DragYPosition = yMaxBounds;
    }

    rectTransform.anchoredPosition = new Vector2(DragXPosition, DragYPosition);
}
kodarr
  • 1
  • 2