I want to put a limit on the edges of the screen for dragable objects
// Hi, my code is working fine but I want put a limit on the edges of the screen so that the dragged object don't go outside of the screen. How do I do that? Here's my code.
void OnMouseDown() { if (IsDragable == true) { screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, 0, screenPoint.z));
}
}
void OnMouseDrag()
{
if (IsDragable == true)
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, 0, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
}
Answer by BrandonD · Jun 13, 2019 at 04:02 AM
After that code, you could simply put something like
if(curPosition.x>maxPositionX)
{
curPosition.x=maxPositionX;
}
if(curPosition.x<minPositionX)
{
curPosition.x=minPositionX;
}
if(curPosition.y>maxPositionY)
{
curPosition.y=maxPositionY;
}
if(curPosition.y<minPositionY)
{
curPosition.y=minPositionY;
}
And simply define the min and max variables to your hearts content. Keep in mind you may need to take multiple resolutions into account, depending on your platform(s) of choice. Use this reference to help with that if needed:
It doesn't work for me. Do I put right after my code?
if (IsDragable == true) { Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, 0, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
if (curPosition.x > maxPositionX)
{
curPosition.x = maxPositionX;
}
if (curPosition.x < $$anonymous$$PositionX)
{
curPosition.x = $$anonymous$$PositionX;
}
}
Your answer
Follow this Question
Related Questions
Drag an object in one line 1 Answer
How to stop object from going to center of mouse when dragging starts 0 Answers
How to allow clicks to go through Circle Collider 2D on sprite prefab? 0 Answers
2D Drag and Drop, but not when slot is already full 0 Answers
Unity 2D Touch drag specific Object 0 Answers