我使用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