- Home /
Moving child and parent
hi,
I'm stuck on how I can get a child to move but keeping the parent at the same distance once its move to the child, so if the child is at 0,0,0 and the parent distance is 9,9,0, but I move the child to 100,100,0. I want the parent to be at 109,109,0 when I move it to the child's position. basically, I want the distance kept the same where ever I move the child.
any help would be highly appreciated.
The child is local to the parent not vise versa, can you switch them around so the parent is the child and the child is the parent? If not you would have to get the position where you want the child, position the parent there, add the offset to the parent and take away the offset locally from the child.
Or just get the offset between child position and final child position and add it to the parent.
void $$anonymous$$ove(Vector3 finalPosition)
{
var offset = finalPosition - child.Position;
parent.Position = parent.Position + offset;
}
But would that not take the child with it, thus making the distance between the two objects still too far apart? It's hard to tell exactly what Shaz is looking for without more context, but if they want the parent to remain the same amount of distance away from the child, it's the parent that needs to be moved, not the child. Which, pending that the script doing the moving is on the child, could be done with something like:
public Vector3 parentTarget;
GameObject ParentObject;
void Start()
{
ParentObject = GetComponentInParent<GameObject>();
}
private void Update()
{
ParentObject.transform.position = parentTarget;
}
Answer by darkStar27 · May 07, 2019 at 05:48 AM
One thing you can do is save your position difference to a variable, and add it to your parent whenever you move you child.
/*
Script is attached to parent
*/
public Vector3 parentOffset;
void Awake(){
parentOffset = GetComponentInChildren<Transform>().localPosition;
}
void Update{
// If targetPosition is varible that contains the position that is to be moved at then
// move you child at targetPosition
// move you parent at targetPosition+parentOffset;
}
// just remember targetPosition is also a Vector3.
Hope this helps.
Please tell us, is the child moving by scripting? By physics/collisions etc?
Why don't you just swap the child <-> parent by scripting so you can control that automatically?
something like this perhaps.
what I am doing is using a start point as a child and trying to get the parent offset to the child and then moving them both to a different position but keeping the offset. I have it so far working with some of the items with remember local offset and then moving it but I have two items not working.