libGDX: How to let the camera point to moving sprite?
Asked Answered
P

3

5

I'm new to libGDX and android game dev. And I want to achieve this: I have a Screen and within it, a ball sprite that is moving along the X axis. Now I want to center the viewport to the sprite when it moves. Just like in Angry birds, where the camera follows the bird flying across the sky.

How can I implement that within my game using OrthographicCamera?

Poesy answered 26/7, 2012 at 9:58 Comment(0)
L
12

This took me a while of Googling and testing, but I just found something and I think others may appreciate it.

To move the camera (and if you are using a spriteBatch), make sure to call setProjectionMatrix.

Ex:

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!

Lovellalovelock answered 24/8, 2013 at 13:29 Comment(0)
F
3

In case you haven't figured this out yet, you need to convert the ball position to the camera position using

camera.unproject(ballPosition)

This converts the screen coordinates into world coordinates. Then call

camera.position(ballPosition) 

to set the camera position to your ball's location in the world.

Fisher answered 3/10, 2012 at 20:28 Comment(0)
D
2

The

camera.translate(...);

function translates all of the involved attributes the camera by the given data. After the operation you need to call

camera.update();

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

Douala answered 19/4, 2013 at 11:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.