Monogame: создание функции рисования в классе - PullRequest
0 голосов
/ 28 января 2019

Я хочу создать класс плиток, который содержит собственную функцию рисования.Ниже то, что я имею до сих пор.Ошибка, которая отображается при запуске кодера:"System.InvalidOperationException: 'Begin не может быть вызван снова, пока End не был успешно вызван."Это сообщение об ошибке отображается в spirteBatch.Begin () внутри класса.

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);
    }
}

}

Текстура 1920x1080, и я протестировал рисование и обрезку, и она работала нормально.

1 Ответ

0 голосов
/ 29 января 2019

Прежде всего, ваш код, вероятно, неполон, но вы никогда нигде не вызываете метод draw.

Допустим, вы вызываете его, вы уверены, что ваша текстура больше 300x300?И что содержится в этой текстуре (x, y = 300 300 x, y = 400 400)?Есть ли у него какие-либо данные о цвете в этих позициях?

Если вы ответите «да» на все это, нам потребуется больше кода, чтобы помочь вам в этом.

Боковой узел: с тех порэто плитка, вы, вероятно, собираетесь рендерить многие из них.Вам не нужно вызывать .Begin () и .End () для всех из них.Просто вызовите Begin () до первого тайла и End () после последнего, и все готово.Это сделает рендеринг намного быстрее.

...