Why isn't drawing a Sprite working?

Hi everyone. I’m having an issue, and it’s really frustrating because of how simple it is :stuck_out_tongue: . Drawing a Sprite isn’t working at all. I’m using LibGDX.

For example, with this code, when I draw the sprite, it is flashing really fast.

@Override
	public void show() {
		batch = new SpriteBatch();

		texture = new Texture("ui/mainmenu.png");
		mainMenu = new Sprite(texture);
		mainMenu.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
		
		batch.begin();
		mainMenu.draw(batch);
		batch.end();
	}

	@Override
	public void render(float delta) {
		Gdx.gl.glClearColor(0, 0, 0, 1);
	    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
	}

but with this code, my sprite doesn’t show up at all.

	@Override
	public void show() {
		batch = new SpriteBatch();

		texture = new Texture("ui/mainmenu.png");
		mainMenu = new Sprite(texture);
		mainMenu.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
	}

	@Override
	public void render(float delta) {
		Gdx.gl.glClearColor(0, 0, 0, 1);
	    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
	    
	    batch.begin();
	    mainMenu.draw(batch);
	    batch.end();
	}

Thanks in advance :slight_smile:

Your first bit of code doesn’t render the sprite in your render() loop. You are incorrectly trying to draw in your show() method.

Also, you should probably not create new textures and sprite batches in a method called “show()” unless you are absolute sure it will only be getting called once. Expensive things like texture creation should be done at startup, not more than necessary.

The second bit of code looks like it would work. You might need to use a ortho projection matrix, like this…

create …
    cam = new OrthographicCamera();

resize…
    cam.setToOrtho(false, width, height);

render …

    batch.setProjectionMatrix(cam.combined);
    ///now render your batch

Try changing it to this:


new Texture(Gdx.files.local("ui/mainmenu.png"));

I played around with it for a little bit, and I found the issue, but didn’t solve it.

Pretty much, the main game class sets the screen to MainMenu. MainMenu then runs its show method once then never runs its render method, and switches back to the main game class render method. Why is it doing this?

I have no idea what to do here because I’ve tried copying and pasting code from another screen class I made for a different project, pasting it in, then changing all the names and everything, and it still doesn’t work.

EDIT: I figured out the issue. I had to add super.render(); to the main game class. Ugh, I can’t believe I forgot that, and was trying to figure out the problem for a couple hours now DX. I guess that’s programming though :wink: