- Home /
How do i prevent the player from dragging a ui element off screen?
here is the code.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
namespace QInventory
{
[AddComponentMenu("Q Inventory/Q UI Drag")]
public class Q_UIDrag : MonoBehaviour, IBeginDragHandler, IDragHandler
{
private Vector2 offset;
public void OnBeginDrag(PointerEventData eventData)
{
offset = eventData.position - (Vector2)transform.position;
transform.position = eventData.position - offset;
}
public void OnDrag(PointerEventData eventData)
{
transform.position = eventData.position - offset;
}
}
}
Answer by tormentoarmagedoom · Oct 05, 2019 at 06:11 PM
Hello there.
You can always knwo the position of the mouse on the screen with
https://docs.unity3d.com/ScriptReference/Input-mousePosition.html
So you block the drag if mouse reach the border or something like this.
Hi, ty for taking ur time to comment on this. i did try to fix it with the mouse position but couldnt find a way to make some sort of border to block it. btw eventData.position is same as mouse pos since i use it to make the inventory follow it.
Your answer
Follow this Question
Related Questions
How do you change gravity with a press of a button? Unity 2D 2 Answers
Image as boundary 1 Answer
Screen scaling causing text to be outside button 0 Answers
Virtual Joystick jump in unity2d 0 Answers
How to shrink text size 1 Answer