Abbas Nikzad Abbas Nikzad - 1 year ago 286
C# Question

Keep child object inside parent in Unity3D

I have a

to make a border in my 2D game. I have another
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
they dont go beind my special Border that is a

I have tried to do this before by using 2
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 Source

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
    // 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;
    // ignore


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download