0
votes

I've been writing a Parent/Child Entity system for a small game and I am having a problems when I try to get a child object's location.

As it stands now, the child of an Entity are transformed, rotated, and scaled in the coordinate space of the parent. This means that if our parent is at a location of ( 2, 3, 0 ) and we add a child to that parent at a location of ( 1, 2, 1 ), its world space is ( 3, 5, 1 ).

My problem is that I don't know how to convert from the local space ( 1, 2, 1 ), to the global space ( 3, 5, 1 ).

The obvious place to start is by adding the parent position and the child position. This works for non-rotated objects. Whenever rotation and scale are applied though it gets confusing and this is what I cannot figure out.

I read somewhere to use inverse of matrices but the explanation beyond that was not clear. Any help/mathematical insight/pseudocode would be greatly appreciated, thanks!

2

2 Answers

1
votes

Just wanted to post this in case it helped anyone cause it caused me quite a bit of confusion.

This is actually very simple to do. All you have to do is multiply the parent entities model matrix by the child's model matrix then recover the coordinates from the bottom row like so.

In the example below we can see how I get the position from the model matrix of an entity with and without a parent. ( I do not actually do this. I store the position of each entity separately. This is just useful for entities that you know have a parent and need the position in the world space. )

Vector3f Entity::GetPosition() const {
    Matrix4f matrix;
    if ( GetParent() != 0 ) { 
        matrix = GetParent()->GetModelMatrix() * GetModelMatrix();
    } else {
        matrix = GetModelMatrix();
    }

    float x = matrix[ 3 ][ 0 ];
    float y = matrix[ 3 ][ 1 ];
    float z = matrix[ 3 ][ 2 ];

    return Vector3f( x, y, z );
}

Note: I wrote my own matrix implementation so how you multiply and extract the positions will most likely be different.

0
votes

The underlying concept used here is change in basis of matrix. Using the axis vectors of the local coordinate system and coordinates with respect to the local coordinate system , the coordinates at global system can be obtained.

a = [a']M

a' - Coordinates wrt local axis
M  - Basis matrix formed using vectors of axis

I found videos which explain the same in great detail .

Links :

1) https://youtu.be/zntNi3-ybfQ

2) https://youtu.be/1j5WnqwMdCk