如何让玩家留在屏幕上而不是在libgdx中退出屏幕?

时间:2017-05-19 03:09:29

标签: android libgdx screen

当我使用加速度计和键盘输入左右移动时,如何让我的播放器保持在屏幕上? This image explained my problem

以下是我的代码

 // 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;

渲染

   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>

谢谢并提前:)我是这个框架的新手。

1 个答案:

答案 0 :(得分:0)

下面的代码看起来很似似:

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

应该是这样的:

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

libgdx中的游戏对象,如SpriteImage或任何其他可绘制对象,其x坐标位于左侧底部。