[LibGDX] Drawing sprite on scrolling map [Solved]

Hello there! New member in JavaGaming. :slight_smile:

And the best way to start in a community is with a good coding question xD Well, my problem is the following: I’m working with LibGDX. I’ve loaded a .tmx map with a camera. Changing the value of camera.position I can move the camera to see the map. Now, I want to draw an sprite over the map. And I did the following:

  • First I tried with batch.draw, using some vector calculus. The object is drawn well in its initial position, but when I move the camera, it goes crazy. I think my vector calculus is well-done…

  • After that, I read that I can use batch.setProjectionMatrix(camera.combined); to do the camera move. Of course, using this method I can’t use a batch.draw() but a sprite.draw(batch). That’s what I’ve done, but, if a write the batch.setProjectionMatrix line, it won’t draw. Here’s my code:

public void render(SpriteBatch batch, float stateTime)
{
		currentFrame = anim.getKeyFrame(stateTime, true); //Get animation frame
		sprite.setPosition(getDrawCoords().x, getDrawCoords().y); //set the position (drawn without the batch.setProjection)
		sprite.setSize(currentFrame.getTexture().getWidth()/2, currentFrame.getTexture().getHeight());  //set a size
		sprite.setRegion(currentFrame); //set the currentframe
		sprite.draw(batch); //...and draw
	}
	
	public Vector2 getDrawCoords()
	{
		int x =  (int) (map.camera.viewportWidth/2-map.camera.position.x + map.tilePixelWidth * xMap); //xMap: tile x
		int y = (int) (map.camera.viewportHeight/2-map.camera.position.y+ map.tilePixelHeight * yMap); //yMap: tile y
		return new Vector2(x,y);
	}

EDIT: This piece of code is my class’ render method, NOT the main render method. The main is this:

@Override
	public void render() {		
		Gdx.gl.glClearColor(1, 1, 1, 1);
		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
		
		map.update(); //control the camera
		stateTime += Gdx.graphics.getDeltaTime();
		map.render(); //render the map (include camera.update()
		batch.setProjectionMatrix(camera.combined); //if this is here, my sprite is not drawn.
		batch.begin();
		units.get(0).render(batch, stateTime); //the above render method
		batch.end();
		
		
	}

Please note the left down corner of the map is drawn at (camera.viewportWidth/2, camera.viewportHeight/2) so you have to take that coordinate as the (0,0).

I don’t know what to do. I’ve proved lot of coordinates but it is never drawn when I write that line. Any help is appreciated.
Thank you very much!! :smiley: