I want a border limit from which an object can be moved, c#

Hello,

I am making a game and I have a script where I can move my object around the screen, but I want it so the object can only be moved inside a border. I followed this tutorial on how to make movable objects: Unity New UI : How To Build Draggable UI - YouTube

I was thinking using a Trigger 2D Box collider so the object can only move inside that collider, but I’m not sure how to implement that into my script. Here is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIDrag : MonoBehaviour {

    float OffsetX;
    float OffsetY;

    public void BeginDrag() {
        OffsetX = transform.position.x - Input.mousePosition.x;
        OffsetY = transform.position.y - Input.mousePosition.y;
    }

    public void OnMouseDrag()
    {
        transform.position = new Vector3(OffsetX + Input.mousePosition.x, OffsetY + Input.mousePosition.y);
    }
}

I used the EventTrigger component for the script:
alt text

Will someone please help me?

Umm, you could add said collider and do the movement inside OnTriggerStay2D.

For this, you would need a few changes :

  • Set collider as trigger, don’t need collisions with game objects
  • Inside OnMouseDrag, set a variable to true, so we know we are dragging something
  • Inside OnTriggerStay2D, if dragging, change element position.

Since the movement is done inside OnTriggerStay2D, the movement will only apply if the drag is inside the collider area.

That said, the collider doesn’t collide with mouse cursors, you will need some invisible collidable object following the mouse for the trigger to activate. Best practice would be a ghost element. A preview of the element to move so the user can see where it will be placed.

Why dont you just clamp the postion ?

public float minX = -10;
public float maxX = 10;

public float minY = -10;
public float maxY = 10;

public void OnMouseDrag()
     {
         transform.position = new Vector3(OffsetX + Input.mousePosition.x, OffsetY + Input.mousePosition.y);

     Vector3 newPosition = transform.position;
     newPosition.x = Mathf.Clamp(newPosition.x, minX, maxX);
    newPosition.y = Mathf.Clamp(newPosition.y, minY, maxY);

   transform.position = newPosition;
     }