如何将播放器放在libgDX相机的中心

时间:2013-07-30 00:46:13

标签: java camera libgdx side-scroller

我刚刚开始使用libGDX来制作游戏,我正在尝试使用正交相机来移动玩家(制作2D侧卷轴)。出于某些原因,我不明白当我做所有应该让相机在屏幕中央绘制播放器时,播放器被略微向右上角移动。

我整天都在寻找不同的东西,但我没有找到任何解决方案。

如果它有助于我的播放器精灵是方形128 x 128图像,我的显示器尺寸是1366x768

这是我的gameScreen代码:

 package com.inertiafall.inertiaengine.screens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Vector3;
import com.inertiafall.inertiaengine.InertiaEngine;
import com.inertiafall.inertiaengine.InputHandler;
import com.inertiafall.inertiaengine.entities.Player;

public class GameScreen implements Screen {
    InertiaEngine game;
    SpriteBatch batch;
    Player player;

    OrthographicCamera cam;
    float width, height;
    ShapeRenderer sr;

    public GameScreen(InertiaEngine game){
        this.game = game;
    }

    public void show() {    
        player = new Player(5, 5);  
        player.init();
        width = Gdx.graphics.getWidth();
        height = Gdx.graphics.getHeight();

        cam = new OrthographicCamera(width, height);
        cam.setToOrtho(false);
        cam.position.set(player.getX(), player.getY(), 0);
        cam.update();

        batch = new SpriteBatch();
        batch.setProjectionMatrix(cam.combined);


        sr = new ShapeRenderer();
    }

    public void update(float delta){
        checkKeys();
        player.update(delta);
        cam.position.set(player.getX(), player.getY(), 0);
        cam.unproject(new Vector3(player.getX(), player.getY(), 0));
        cam.update();
        batch.setProjectionMatrix(cam.combined);    
        sr.setProjectionMatrix(cam.combined);
    }

    public void render(float delta) {
        update(delta);  
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        batch.begin();
        player.render(batch);
        batch.end();        

        sr.begin(ShapeType.Line);
        player.renderDebug(sr); 
        sr.end();
    }

    public void resize(int width, int height) {

    }

    //check key events  
    private void checkKeys(){       
        if(InputHandler.keyPress(InputHandler.getExitKey())){
            exit();
        }
    }

    //key events
    private void exit(){
        Gdx.app.exit();
    }

    public void hide() {
        dispose();
    }

    public void pause() {}

    public void resume() {}

    public void dispose() {
        batch.dispose();
        player.dispose();
        sr.dispose();
    }

}

1 个答案:

答案 0 :(得分:2)

我认为可能是您将相机设置为player.getX()或getY()的位置。 X和Y值指向玩家精灵的角落。尝试将相机设置为

player.getX() + (player.getWidth() / 2)

player.getY() + (player.getHeight() / 2)

应该是玩家精灵的中心。