LibGDX: How to include a camera in a moving sprite?

I am new to libGDX and a game developer for Android. And I want to achieve this: I have a Screen and inside it is a sprite of a ball that moves along the X axis. Now I want to focus the viewport on the sprite when it moves. As in Angry birds, where the camera follows a bird flying through the sky.

How can I implement this in my game using OrthographicCamera ?

+4
source share
3 answers

It took me some time to googling and testing, but I just found something, and I think others can appreciate it.

To move the camera (and if you use spriteBatch), be sure to call setProjectionMatrix.

Example:

 camera.position.y += 5; // or whatever you want to change y by... camera.position.x += 5; camera.update(); spriteBatch.setProjectionMatrix(camera.combined); 

Hope this helps someone!

+11
source

If you still do not understand this, you need to convert the position of the ball to the position of the camera using

 camera.unproject(ballPosition) 

This converts the screen coordinates to world coordinates. Then call

 camera.position(ballPosition) 

to set the position of the camera to the position of your ball in the world.

+3
source

 camera.translate(...); 
Function

translates all involved camera attributes according to data. After surgery you need to call

 camera.update(); 

to calculate new camera matrices. This will push the camera to the direction you need.

+2
source

All Articles