I've been fighting with this for a while now. The idea is for the players to drag a child around its parent along the x axis. I don't want them to be able to move it outside the left or right side. For the most part the code stops them from dragging outside to the left but once it does it, they can no longer drag it back the other way. I tried adding a BoxCollider2D to the parent figuring it would prevent it from moving past the bounds but it doesn't. I have a CapsuleCollider2D on the child objects.
public class DragDrop : MonoBehaviour
{
private Vector3 mOffset;
private float mZCoord;
void OnMouseDown()
{
mZCoord = Camera.main.WorldToScreenPoint(
gameObject.transform.position).z;
// Store offset = gameobject world pos - mouse world pos
mOffset = gameObject.transform.position - GetMouseAsWorldPoint();
}
private Vector3 GetMouseAsWorldPoint()
{
// Pixel coordinates of mouse (x,y)
Vector3 mousePoint = Input.mousePosition;
// z coordinate of game object on screen
mousePoint.z = mZCoord;
// Convert it to world points
return Camera.main.ScreenToWorldPoint(mousePoint);
}
void OnMouseDrag()
{
var pos = GetMouseAsWorldPoint() + mOffset;
var minX = GetComponent<SpriteRenderer>().bounds.min.x;
var maxX = GetComponent<SpriteRenderer>().bounds.max.x;
var minXp = transform.parent.GetComponent<SpriteRenderer>().bounds.min.x;
var maxXp = transform.parent.GetComponent<SpriteRenderer>().bounds.max.x;
if (minXp < 0)
{
if (minX < minXp)
{
return;
}
}
else if (maxX > maxXp)
return;
transform.position = new Vector3(pos.x, transform.position.y, transform.position.z);
}
}