Reputation: 43
I am wanting to make a tile class that contains it's own drawing function. Below is what I have so far. The error that is showing when I run the coder is. "System.InvalidOperationException: 'Begin cannot be called again until End has been successfully called." This error message shows up on the spirteBatch.Begin() inside the class.
namespace TileGame.v3
{ class Tile {
public Texture2D texture { get; set; }
public int X { get; set; }
public int Y { get; set; }
public int sourceX { get; set; }
public int sourceY { get; set; }
public int width { get; set; }
public int height { get; set; }
public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
spriteBatch.Begin();
spriteBatch.Draw(texture, new Vector2(X, Y), new Rectangle(sourceX, sourceY, width, height), Color.White);
spriteBatch.End();
Draw(gameTime, spriteBatch);
}
}
}
namespace TileGame.v3
{
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D mark;
Texture2D peep1;
Texture2D ocean;
int x1 = 100;
int y1 = 100;
int x2 = 400;
int y2 = 400;
int tempx;
int tempy;
bool win = false;
Tile a = new Tile();
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
mark = Content.Load<Texture2D>("mark");
peep1 = Content.Load<Texture2D>("peep1");
ocean = Content.Load<Texture2D>("ocean");
a.texture = ocean;
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
if (Keyboard.GetState().IsKeyDown(Keys.Enter))
{
tempx = x1;
x1 = x2;
x2 = tempx;
tempy = y1;
y1 = y2;
y2 = tempy;
win = true;
}
a.X = 100;
a.Y = 100;
a.sourceX = 300;
a.sourceY = 300;
a.width = 100;
a.height = 100;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
spriteBatch.Begin();
a.Draw(gameTime, spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
The texture is 1920x1080 and I have tested drawing and cutting it and it has worked fine.
Upvotes: 0
Views: 857
Reputation: 586
First of all, your code is probably incomplete, but you are never calling the draw method anywhere.
Let say you are calling it, are you sure your texture is bigger than 300x300? And what does that texture contains for (x,y = 300,300 to x,y = 400,400)? Does it have any color data in those positions?
If you answer yes to all of this, we will need more code to be able to help you with that.
Side node: Since this is a tile, you probably are going to render many of them. You don't need to call .Begin() and .End() for all of them. Simply call Begin() before the first tile and End() after the last one and you're good to go. This will make rendering much faster.
Upvotes: 1