# Tree of objects in 2D space - children relative to parent

### Question

How do we track the position of child objects, relative to a parent?

### Context

I have a simple structure that keeps track of a point in space, along with zero or more children:

function Point(x, y){
this.x = x;
this.y = y;
this.children = [];
}

Given the relationship:

const a = new Point(100, 100);
const b = new Point(10, 10);
a.children.push(b);

When these are rendered, I want point b to render at world location [110, 110].

After moving a and only a:

a.x += 10;

Both points move and the distance between the two must remain the same.

After moving b and only b:

b.x += 10;

Only b moves and the distance between both points must now be different.

In other words, a child's (x, y) is the same as its offset from its parent.

With transform hierarchies (trees), the normal method is to work your way up or down the tree, applying any transformations of the parent to the child, at each level, till you have processed everything. Given you aren't concerned with issues like rotation/orientation or scaling, i.e. you're purely interested in translation, it's very simple:

//...do your parent-child links and set up the offset (localPosition) for each node...

root.worldPosition = root.localPosition; //root has no parents so no nested translation
root.TransformChildren();

this.TransformChildren = function()
{
for (var childKey in this.children)
{
var child = this.children[childKey];
child.worldPosition = child.localPosition + child.parent.worldPosition;
child.TransformChildren(); //child is the new parent
//...its children can now add its position to their own to arrive at final value
}
}

Notice that we use pre-order depth-first traversal to solve the problem. This is so that the parent positions have already been calculated for the children to use once we get down to the child level. You could use breadth-first search too, but DFS is just simpler in this instance.