2
votes

I've been trying to create a game where there's a person falling. The size of my background texture is 480x3200, and I'm trying to create the game so that the camera keeps the person in the middle of the screen while falling down, and then stops at the bottom. But I can't get my background is extend beyond the screen it starts in, and then be able to see the rest of the image.

All of my code does right now is scale down the 480x3200 image down to fit onto my current screen (which I set to be 480x800), and then as the person falls, the background doesn't change.

Here's my WorldRenderer class where I've tried to do different things but every time, I can never get the person to see a different part of the image when it starts moving down.

    public WorldRenderer(SpriteBatch b, World w) {
    this.world = w;
    this.cam = new OrthographicCamera(CAMERA_WIDTH, CAMERA_HEIGHT); 
    this.cam.position.set(CAMERA_WIDTH / 2, Person.position.y,0);
    this.cam.setToOrtho(false, CAMERA_WIDTH, CAMERA_HEIGHT);
    this.cam.update();
    spriteBatch = b;
    loadTextures();
}

public void render(float delta) { 
    person = world.getPerson();

    moveCamera(); 
    cam.update();
    spriteBatch.setProjectionMatrix(cam.combined);

    spriteBatch.disableBlending();
    spriteBatch.begin();
    renderBackground();
    spriteBatch.end();

    spriteBatch.enableBlending();
    spriteBatch.begin();
    renderObjects();
    spriteBatch.end();

}

private void moveCamera() {
    cam.position.set(cam.position.x, Person.position.y, 0); 
    cam.update();
}

private void renderObjects() {  
    renderPerson();
    renderBlocks();
    renderPlatforms();
}

private void renderBackground() {
    spriteBatch.draw(backgroundTexture, cam.position.x - CAMERA_WIDTH / 2, cam.position.y - CAMERA_HEIGHT / 2, CAMERA_WIDTH, CAMERA_HEIGHT);
}   
}

Does anyone have any suggestions?

Edit: Thanks, I changed the draw in renderBackground to spriteBatch.draw(backgroundTexture,0,0, CAMERA_WIDTH, CAMERA_HEIGHT * 4); and it works now.

2

2 Answers

1
votes
spriteBatch.draw(backgroundTexture, cam.position.x - CAMERA_WIDTH / 2,
    cam.position.y - CAMERA_HEIGHT / 2, CAMERA_WIDTH, CAMERA_HEIGHT);

This code is drawing the background image relative to the camera's position. That's why changing the camera's position has no effect on the background image's position. Change it to something like this:

spriteBatch.draw(backgroundTexture,0,0);
1
votes

Or u can simply use ParrallaxBackground and ParrallaxLayer class

This way u dont have to manage ur camera

Its done in an optimized manner in the mentioned class.