- Home /
how to move child object inside a moving parent in 2d using Vector2.MoveTowards()?
The Parent object is a moving rectangle and inside the rectangle there is another rectangle. the parent moving to right continuously and the child rectangle moving up and down.
(I Nested The Child into The Parent)
i need the child move just inside the parent and don't cross the borders of its parent by using Vector2.MoveTowards()?
Answer by Bunny83 · Feb 07, 2018 at 12:08 PM
Uhm, just use child.localPosition
and use a local position inside the parent space as target point. If you want to prevent the object from leaving or intersecting the border of the parent you just have to choose target points which are inside the parent. You presented this problem in a very generic / abstract way.
Lets assume the pivot of the parent is the center of the parent and the pivot of the child is the center of the child. We also assume that the parent and child objects have a scale of (1,1,1). We further assume that the parent rect has a side length of xS and yS and the child object has a size of xSc and ySc.
That means the local y coordinate inside the parent goes from border to border:`+yS/2` to -yS/2
. However since the child has a height of "ySc" we have to subtract half that from the possible target range. So the valid range for the child goes from (yS - ySc)/2
to -(yS - ySc)/2
on the y axis.
actually my main concern is how to move the child inside the moving parent(regardless of the border crossing). I simply wrote a script that moves the gameobject that attached to specific point :
public float speed = .5f;
public Vector2 moveToPoint;
void Update()
{
transform.localPosition = Vector2.$$anonymous$$oveTowards(new Vector2(transform.localPosition.x, transform.localPosition.y),
new Vector2(transform.parent.transform.position.x + moveToPoint.x, transform.parent.transform.position.y + moveToPoint.y), speed * Time.deltaTime);
}
assume you attach this script to a non-child object. it simply moves the object from original position to the "$$anonymous$$oveToPoint" point. but if you attach this script to a child object of a moving parent, the "$$anonymous$$oveToPoint" point is far away from the child object. how can i prevent that issue?
That's because you don't use a "local position" inside the parent. You use the world space position of the parent which of course doesn't make any sense. As i said your target point has to be a point relative to the parent space. It looks like you just want:
transform.localPosition = Vector2.$$anonymous$$oveTowards(transform.localPosition, moveToPoint, speed * Time.deltaTime);
given that movePoint is a relative point inside the parents local space.
Your answer
Follow this Question
Related Questions
Local position issue 0 Answers
Lerp a Child but 'keep up locally' with Parent 0 Answers
Get Prefab In Nested Prefab 1 Answer
How to get the world position of the edge of an object? 2 Answers
Make a simple tree 1 Answer