I’m using C# and XNA 4.0, as well as Farseer Physics Engine (very similar to Box2D), and have a Block class from which I derive OBlock, LBlock, etc.
Block is as follows:
class Block
{
public Body m_body;
public virtual void Draw(SpriteBatch spriteBatch) { }
public virtual void RemoveBody(World world)
{
//world.RemoveBody(m_body);
}
}
I’ve only put those methods, fields, etc in so I can access their overridden versions in a List
So my overridden versions look something like this:
OBlock.cs
class OBlock : Block
{
private static Texture2D blockImg; //I load this in LoadContent so I don't have loads of Texture2Ds
public new Body m_body; //Is this right?
public OBlock(World world, Vector2 position)
{
m_body = BodyFactory.CreateBody(world, position); // Create the body, changing it from null
FixtureFactory.AttachRectangle(Game1.blockSide *2, Game1.blockSide *2, 1.0f, new Vector2(0, 0), m_body); //This bit changes between classes
m_body.BodyType = BodyType.Dynamic;
}
public override void RemoveBody(World world)
{
world.RemoveBody(m_body);
}
public static void LoadImage(Texture2D tex)
{
OBlock.blockImg = tex;
}
public override void Draw(SpriteBatch spriteBatch)
{
Vector2 position = m_body.Position * Game1.MetreInPixels;
Vector2 origin = new Vector2(blockImg.Width / 2, blockImg.Height / 2);
float rotation = m_body.Rotation;
spriteBatch.Begin();
spriteBatch.Draw(blockImg, position, null, Color.White, rotation, origin, Game1.BLOCK_SCALE, SpriteEffects.None, 1);
spriteBatch.End();
base.Draw(spriteBatch);
}
}
There’s also LBlock, ZBlock, etc which all look very similar apart from the bit I commented.
I then have them all in
List<Block> blocks //As a field in Game1
blocks = new List<Block>(); // In LoadContent after loading images
What I’m trying to do is access m_body for any Block in the list regardless of type using
blocks[index].m_body.DOSTUFF();
Apparently m_body is always null…
This is not right. The
m_bodyfrom yourBlockclass (which you should markabstractbtw) is visible in all classes deriving from it. What you’re doing right now is called hiding (which should always be avoided imo), which causes various complications.You’ve now made it so that each
OBlockhas two membersm_body, one belonging toBlock, one belonging toOBlock. It makes it so that any time you referencethis.m_bodyin yourOBlockclass, you’re assigning them_bodyfield belonging toOBlock, leavingm_blockdeclared inBlockalone. This is one of the weird complication that comes with hiding members:Whereas this would work as expected:
So avoid hiding! Remove
from your code file and you’re good to go, because
m_blockdeclared inBlockis inherited by all classes deriving from it anyway.