patterncsharpMinor
Cascading a property for a game
Viewed 0 times
propertygameforcascading
Problem
I'm trying to write a simple game. I have an
Here's a simplified example of creating an
Most of the Sprites have the same position, so I do this instead:
Notice the halo sprite is in a different position. Later in the code, I call the
The
Entity object, that has a list of Sprite objects. Each Sprite has a position property where it is drawn on the screen. Sometimes, an entity can contain a lot of Sprites in which case it is much easier to set the position property on the parent Entity.Here's a simplified example of creating an
Entity with a list of Sprites:var player = new Entity( new List
{
new Sprite( "characters/walkcycle/body", new Vector2( 128, 128 ) ),
new Sprite( "characters/walkcycle/halo", new Vector2( 128, 120 ),
new Sprite( "characters/walkcycle/shirt", new Vector2( 128, 128 ) ),
new Sprite( "characters/walkcycle/pants", new Vector2( 128, 128 ) ),
new Sprite( "characters/walkcycle/shoes", new Vector2( 128, 128 ) )
} );Most of the Sprites have the same position, so I do this instead:
var player = new Entity( new Vector2( 128, 128 ),
new List
{
new Sprite( "characters/walkcycle/body" ),
new Sprite( "characters/walkcycle/halo", new Vector2( 128, 120 ),
new Sprite( "characters/walkcycle/shirt" ),
new Sprite( "characters/walkcycle/pants" ),
new Sprite( "characters/walkcycle/shoes" )
} );Notice the halo sprite is in a different position. Later in the code, I call the
Load method on Entity, which passes its position property on to the children Sprites:public class Entity
{
// fields, constructor, properties ...
public void Load()
{
foreach ( var sprite in this.sprites )
{
sprite.Load( this.position );
}
}
}The
Load method on Sprite wSolution
Another approach would be to make the positions of sprites relative to the position of the entity. That way, the default of zero comes up naturally and when you move an entity, all of its sprites are automatically moved too.
One more advantage is that this means position zero now becomes a valid one.
One more advantage is that this means position zero now becomes a valid one.
Context
StackExchange Code Review Q#37069, answer score: 8
Revisions (0)
No revisions yet.