I am attempting to get an OrthographicCamera to follow a user controlled sprite. I can't get the camera to properly update position at all. I can't seem to see what is wrong with my code compared to what others have done.
I am still learning and at this point I would assume the problem is being caused by something simple I do not fully understand at this point.
Any help is appreciated, thank you.
This is my renderer:
public class WorldRenderer {
private static final float CAMERA_WIDTH = 10;
private static final float CAMERA_HEIGHT = 7;
private World world;
private OrthographicCamera oCam;
private Hero hero;
ShapeRenderer debugRenderer = new ShapeRenderer();
/** TEXTURES **/
private Texture heroTexture;
private Texture tileTexture;
private SpriteBatch spriteBatch;
private int width, height;
private float ppuX; // Pixels per unit on the X axis
private float ppuY; // Pixels per unit on the Y axis
public void setSize (int w, int h) {
this.width = w;
this.height = h;
ppuX = (float)width / CAMERA_WIDTH;
ppuY = (float)height / CAMERA_HEIGHT;
}
public WorldRenderer(World world, boolean debug) {
hero = world.getHero();
this.world = world;
spriteBatch = new SpriteBatch();
oCam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
oCam.update();
loadTextures();
}
private void loadTextures() {
tileTexture = new Texture(Gdx.files.internal("images/tile.png"));
heroTexture = new Texture(Gdx.files.internal("images/hero_01.png"));
}
public void render() {
oCam.update();
spriteBatch.begin();
spriteBatch.disableBlending();
drawTiles();
spriteBatch.enableBlending();
drawHero();
spriteBatch.end();
}
private void drawHero() {
spriteBatch.draw(heroTexture, hero.getPosition().x * ppuX, hero.getPosition().y * ppuY, Hero.SIZE * ppuX, Hero.SIZE * ppuY);
oCam.position.set(hero.getPosition().x, hero.getPosition().y, 0);
}
}
SpriteBatch manages its own projection and transformation matrixes. So, you have to set its matrixes (if possible, before calling begin()).
Unless you need to access your matrixes separately (projection and model-view, eg. in shaders), setting the projection matrix to the projection-model-view matrix will be enough.
Anyway, this should work in your code:
oCam.update();
spriteBatch.setProjectionMatrix(oCam.combined);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With