Abbas Nikzad Abbas Nikzad - 20 days ago 7
C# Question

Keep child object inside parent in Unity3D

I have a

Collider2D
to make a border in my 2D game. I have another
Gameobject
inside this border and user can move it up/down by using a virtual Joystick .

Now i want keep all of childs inside this border and when user move them
up/down
they dont go beind my special Border that is a
Collider2D
.

I have tried to do this before by using 2
gameobject
on the top and down of my border for getting the position of them and check each the child objects but if i have more objects it's not a good idea.

What i want to do is like bellow picture

enter image description here

How i can do this ?

Answer

I suggest that you (in your code) always check if your GameObject is inside of your bounds. From there, simply stop modifying the position, when it is out of the bounds.

PolygonCollider2D poly = transform.parent.GetComponent<PolygonCollider2D>();
// Check if the position is inside of the bounds
if (poly.bounds.Contains(transform.position))
{
    // GameObject is inside of the bounds
}
else 
{
    // GameObject is outside of the bounds!
}

A quick example of how you would do it:

Vector2 movement;
// Calculate movement here
Vector2 newPosition = transform.position + movement;
PolygonCollider2D poly = transform.parent.GetComponent<PolygonCollider2D>();
if (poly.bounds.Contains(newPosition))
{
    transform.position = newPosition;
}
else 
{
    // ignore
}

Edit:

Because we are trying to get Bounds.Contain of 2DCollider we must check the Vector2 position of GameObjects