0
\$\begingroup\$

I'm writing a simple game in C# and i'm having some difficulty to calculate the local position of a sprite.

What i'm aiming to achieve:

  • Calculate the sprite "local position" relative to the parent.

  • When the parent sprite position is changed, the children sprite should be aways following the parent while keeping its relative position.

Example:

Lets assume i have a parent sprite at world position (4, 4) and a children sprite at local position (2, 2), if the parent sprite world position moves to (5, 5), his children local position should be at (3, 3).

Below is a example code of what i'm trying to make. Lets assume the parent sprite moved and called UpdateChildrenPositions with his new position, what should the local and world positions of his childrens be?

public class Sprite
{
    public Sprite parent;
    public List<Sprite> childrens;
    
    public Point world_position;
    public Point local_position;
    
    public void UpdateChildrenPositions(Point new_position)
    {
        // What should these numbers contain?
        this.world_position = ???
        this.local_position = ???
    }
}

Could someone provide a direct answer with the math to solve this problem?

Thanks in advance!

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

The parent moving, by definition, does not change the local position. So you only need to change the world position, using the parent's world position and the unchanged local position as the source of truth.

public void UpdateWorldPositionUsingParent() {
    world_position = parent.world_position + local_position;

    // TODO: update positions of any children of this object
    // (grandchildren of our parent).
}

When you want to change the position of an object relative to its parent, you can adjust the world position and local position together:

public void SetPosition(Point newWorldPosition) {
    world_position = newWorldPosition;
    local_position = newWorldPosition - parent.world_position;

     // TODO: update positions of any children of this object
    // (grandchildren of our parent).
}

You can also use a dirty flag to mark objects whose world position is out of date, and update it lazily down the child hierarchy only when needed.

\$\endgroup\$
2
  • \$\begingroup\$ Hello, thanks for the answer. I'll do some testings and see if it works in my project, i'll come back later and report. \$\endgroup\$
    – RickS.
    Commented Aug 25, 2021 at 22:04
  • \$\begingroup\$ I think this is working but i'm having other problems, tomorrow i'll probably post another question, thanks for the answer. \$\endgroup\$
    – RickS.
    Commented Aug 25, 2021 at 23:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .