Search code examples
androidlibgdxscreen

How to make player stay on the screen and not goes out of the screen in libgdx?


How can I make my player stay on the screen when I move it left and right using accelerometer and keyboard input? This image explained my problem

Here is my code bellow

 // Load the sprite sheet as a texture
    cat = new Texture(Gdx.files.internal("catsprite.png"));
    catsprite = new Sprite(cat);
    catsprite.setScale(2f);
    player = new Rectangle();
    player.x = Gdx.graphics.getWidth(); 
    player.y = catPlayerY;

Render

   spriteBatch.draw(currentFrame,player.x, player.y);
   //Keyboard
    if(Gdx.input.isKeyPressed(Input.Keys.DOWN))player.y -= 250 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Input.Keys.UP)) player.y += 250 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) player.x -= 250 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)) player.x  += 250 * Gdx.graphics.getDeltaTime();

   //Mobile acceleration

    if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer)) {
        player.x -= Gdx.input.getAccelerometerX();
        player.y += Gdx.input.getAccelerometerY();
    }
    if (player.x < 0) {
        player.x = 0;
        player.x += Gdx.graphics.getDeltaTime() *20 *delta;
    }
    if (player.x > Gdx.graphics.getHeight()) {
        player.x = Gdx.graphics.getHeight() ;
    }

AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hobocat.game"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="25" />

<application
    android:allowBackup="true"
    android:icon="@drawable/cat_head"
    android:label="@string/app_name"
    android:theme="@style/GdxTheme" >
    <activity
        android:name="com.hobocat.game.AndroidLauncher"
        android:label="@string/app_name" 
        android:screenOrientation="portrait"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <uses-feature
        android:name="android.hardware.sensor.accelerometer"
        android:required="true" />
</application>

</manifest>

Thank's and advance :) I'm new to this framework.


Solution

  • Below codes looks specious :

    if (player.x > Gdx.graphics.getHeight()) {
         player.x = Gdx.graphics.getHeight() ;
    }
    

    It should be like this :

    if (player.x > Gdx.graphics.getWidth()-player.getWidth()) {
         player.x = Gdx.graphics.getWidth()-player.getWidth() ;
    }
    

    Game Objects in libgdx like Sprite, Image or any other drawable objects having x coordinate at left bottom.