Libgdx detect when player is outside of screen
        Posted  
        
            by 
                Rockyy
            
        on Game Development
        
        See other posts from Game Development
        
            or by Rockyy
        
        
        
        Published on 2014-05-29T18:38:45Z
        Indexed on 
            2014/05/29
            22:04 UTC
        
        
        Read the original article
        Hit count: 572
        
Im trying to learn libGDX (coming from XNA/MonoDevelop), and I'm making a super simple test game to get to know it better. I was wondering how to detect if the player sprite is outside of the screen and make it so it is impossible to go outside of the screen edges.
In XNA you could do something like this:
// Prevent player from moving off the left edge of the screen
if (player.Position.X < 0)
    player.Position = new Vector2(0, player.Position.Y);
How is this achieved in libgdx? I think it's the Stage that handles the 2D viewport in libgdx?
This is my code so far:
private Texture texture;
private SpriteBatch batch;
private Sprite sprite;
@Override
public void create () {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();
    batch = new SpriteBatch();
    texture = new Texture(Gdx.files.internal("player.png"));
    sprite = new Sprite(texture);
    sprite.setPosition(w/2 -sprite.getWidth()/2, h/2 - sprite.getHeight()/2);
}
@Override
public void render () {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
        if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT))
            sprite.translateX(-1f);
        else
            sprite.translateX(-10.0f);
    }
    if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
        if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT))
            sprite.translateX(1f);
        else
            sprite.translateX(10f);
    }
    batch.begin();
    sprite.draw(batch);
    batch.end();
}
        © Game Development or respective owner