我使用C#和XNA 4.0以及Farseer Physics Engine(非常类似于Box2D),并且有一个Block类,我从中派生出OBlock,LBlock,等从基类列表中访问派生类的字段
块如下:
class Block
{
public Body m_body;
public virtual void Draw(SpriteBatch spriteBatch) { }
public virtual void RemoveBody(World world)
{
//world.RemoveBody(m_body);
}
}
我只把那些方法,字段等,在这样我就可以访问列表的重载版本
所以我重写的版本看起来像这样: 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);
}
}
还有LBlock,ZBlock等,除了我评论的位之外,它们都非常相似。
我然后让他们都在
List<Block> blocks //As a field in Game1
blocks = new List<Block>(); // In LoadContent after loading images
我试图做的是列表中的任何块访问m_body无论使用
blocks[index].m_body.DOSTUFF();
类型显然m_body总是空。 ...
什么,当你通过一行代码一步一个线,看的对象m_body发生什么呢? – SecurityMatt