recently I started to use XNA with MonoMac.
I have problem with classes.
I want to create a class with textures and position information inside. Also I would like to make draw function.
My idea was to pass spriteBatch and Content arround so I could load textures and draw them afterwards. However Content object i pass into this object doesnt load any textures, when I tried Content outside the class, it loaded textures fine, so textures must be there.
public class TPlayer {
public Texture2D[] textures;
public ContentManager Content;
public SpriteBatch spriteBatch;
public int currentFrame;
public Rectangle position;
public TPlayer(ContentManager ccontent, SpriteBatch cspritebatch){
this.Content = ccontent;
this.spriteBatch = cspritebatch;
this.Content.RootDirectory = "Content";
this.currentFrame = 0;
this.position = new Rectangle(250,20,100,150);
this.LoadContent();
}
protected void LoadContent(){
this.textures[0] = this.Content.Load<Texture2D>("Textures/ToughStanding");
this.textures[1] = this.Content.Load<Texture2D>("Textures/ToughWalking1");
this.textures[2] = this.Content.Load<Texture2D>("Textures/ToughWalking2");
}
public void Draw(){
spriteBatch.Begin (SpriteSortMode.Deferred, BlendState.AlphaBlend);
this.spriteBatch.Draw (textures[0], this.position, Color.White);
this.spriteBatch.End ();
}
This is how i create instance:
Player = new TPlayer(this.Content,this.spriteBatch);
Maybe Im trying to use wrong model.. Maybe I shouldnt want to use spritebatch and Content inside of class, but than can i make spritebatch and content global ?
Thank you for your help
Since you have solved your own problem (nice work!) I’ll use this space to suggest a slightly less resource intensive method of drawing your sprite frames which will also solve the problem you had, instead of using a separate texture for each frame of animation you can combine them in to one single texture. Swapping textures is actually a relatively slow operation.
so instead of 3 textures for Standing, Walking1, Walking2 and using the current frame property to switch between them you can create one large texture to hold all 3, this can be done in paint or any drawing package by simply creating a blank image the size of all 3 frames and copy/paste them in to place (taking note of the start/end positions of each one)
You can create a rectangle array to hold the positions of each sprite in the sheet.
Then to animate the sprite you simply keep track of which rectangle is the current frame.
I’ve attached a quick game class below that shows how the whole operation would work along with a sprite and player class, the sprite class can become the base for all sprites not just the players.
When you want to change the current frame for the player, you call the SetSpriteSheetIndex.
If you wanted to set player zero’s picture to the tough walking 1 frame you would call.