2.4 Parenting sprites

By Charles Quarra, charsquarra@hotmail.com.

Ssuppose you have a few sprites, but you want to build with them some kind of structure. You would like this structure to move as a whole, and every sprite to move relative to the structure. With the knowledge we have now we could acomplish this, but you would have to keep track of the coordinate of the whole structure and every sprite so the whole moves accordingly. That the hard way of doing it. There's an easy way. The idea its creating a hierarchy for the sprites. Think of it as a tree structure (like your directory structure). You can implement this by taking the sprite we have defined in the room and adding other sprites as child sprites.

iMeshWrapper *sprite1 = engine->CreateMeshWrapper (imeshfact, "child1");
spstate = SCF_QUERY_INTERFACE (sprite->GetMeshObject (), iSprite3DState);
spstate->SetAction ("default");
spstate->DecRef ();
sprite1->GetMovable ()->SetPosition (csVector3 (0, -.5, -.5));
sprite1->DeferUpdateLighting (CS_NLIGHT_STATIC|CS_NLIGHT_DYNAMIC, 10);
sprite1->GetMovable ()->Transform (csZRotMatrix3 (PI/3.));
sprite1->GetMovable ()->UpdateMove ();
sprite->GetChildren ()->Add (sprite1);
sprite1->DecRef ();

Now let's see what we are doing here. Note that CreateMeshWrapper() now doesn't contain any iSector* or csVector3 parameters. This is one of the overloaded versions of this function. With this we are instantianting the sprite without adding it to any particular sector. Since we want to add it to a sprite, we have to call it in that way. What is new here are the GetChildren() and Add() methods: sprite->GetChildren() returns a pointer to the iMeshList, which contains all the children of this sprite.
sprite->GetChildren()->Add(sprite1) With this we are adding sprite1 as a child of sprite. Now the csVector3(0,-.5,-.5) is relative to sprite, not the room. Not only any change in position, but any transform we now set on sprite1 will be relative to sprite.