- Home /
How to keep 3d card in bounds of screen when user "drags" it?
hi,
I am trying to make a CCG using 3d cards. I have a simple cube of a card with a box collider.
I am using the OnMouseDrag() method to allow the user to drag the card, and that works fine. But now, I'm trying to keep the card "clamped" to within the bounds of the screen.
I have tried a few different ways but I'm struggling to get it to work reliably. How do I keep the card in bounds of the screen while it's dragging? I am able to keep it "clamped" only if the "center" and "size" values on the Box Collider are unchanged from their original default values.
However, due to the way I'm doing the card art, I need the Box Collider to be offset from the center and have a bigger size.
My logic won't work here because of this. How can I account for the offset (changes in Center.X and Size.X on the Box Collider)?
See my code below which is called at the end of OnMouseDrag():
private void ClampToArea()
{
var coll = GetComponent<BoxCollider>();
var transpos = transform.position;
Vector2 playerPosScreenRightEdge = Camera.main.WorldToScreenPoint(coll.bounds.center + coll.bounds.extents);// transform.position);
Vector2 playerPosScreenCenter = Camera.main.WorldToScreenPoint(coll.bounds.center);
Vector2 originalScreenPos = Camera.main.WorldToScreenPoint(transpos);
float screenCardWidth = (playerPosScreenRightEdge - playerPosScreenCenter).x;
if (playerPosScreenRightEdge.x > Screen.width)
{
Debug.Log("we are past the screen width!");
transform.position =
Camera.main.ScreenToWorldPoint(
new Vector3(Screen.width - screenCardWidth,
originalScreenPos.y,
transform.position.z - Camera.main.transform.position.z));
}
else if (Camera.main.WorldToScreenPoint(coll.bounds.center - coll.bounds.extents).x < 0.0f)
{
transform.position =
Camera.main.ScreenToWorldPoint(
new Vector3(screenCardWidth,
originalScreenPos.y,
transform.position.z - Camera.main.transform.position.z));
Debug.Log("we are before the screen width!");
}
else
{
Debug.Log("ON THE SCREEN OK!");
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612143331im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to move an object X or Y axis only 1 Answer
Rotation of gameobject while dragging on the screen not working as expected in unity 4.6 0 Answers
restrict scaling 2 Answers
Start dragging an UI Image and then keep dragging a 2d collider 0 Answers
"Image.raycastTarget = false" not consistent between PC and Android 1 Answer