如何在libgdx中添加背景图片?

时间:2018-07-14 22:05:13

标签: java libgdx desktop

我想添加一个blockbunny之类的背景,并且在android文件夹下的asset / images文件夹中有一个背景图片image。我试图将图像分为三个部分,并在Background类中将其添加为天空,云彩和山脉。由于某种原因,它抛出了空指针异常,因为在MyMainGame类中spritebatch为null。我已经在MyMainGame类的create方法中初始化了SpriteBatch。

这是我的MyMainGame.class

response.orderNumber == 0;           // true
response.resultingOrders == null;    // true

GameState是一个包含未实现方法的抽象类

public class OrderResponse
{
    public long orderNumber;
    public List<Order> resultingOrders;

    [JsonConstructor]
    public OrderResponse(long orderNumber, List<Order> resultingOrders)
    {
        this.orderNumber = orderNumber;
        this.resultingOrders = resultingOrders;
    }
}

public class Order
{
    public long orderId
    public decimal amount;
    public string type;

    [JsonConstructor]
    public Order(long orderId, decimal amount, string type)
    {
        this.orderId = orderId;
        this.amount = amount;
        this.type; = type;
    }
}

Play类扩展了GameState类

package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.mygdx.manager.Content;
import com.mygdx.manager.GameInputProcessor;

import com.mygdx.manager.GameStateManager;
import com.mygdx.manager.MyInput;


import javafx.scene.layout.Background;

import static com.mygdx.manager.Box2DVariables.PPM;

public class MyMainGame implements ApplicationListener {
    SpriteBatch batch;
    Texture img;
    public static final int Width=320;
    public static final int Height=240;
    public static final int SCALE=2;

    public static final float STEP= 1/60f;  //60 frames per second

    private float accumulator;
    private SpriteBatch sb;
    protected OrthographicCamera cam;
    protected OrthographicCamera hud;
    private Texture tex;
    private Background[] backgrounds;

    private GameStateManager gsm;

    public SpriteBatch getSb() {
        return sb;
    }

    public OrthographicCamera getCam() {
        return cam;
    }

    public OrthographicCamera getHud() {
        return hud;
    }
     public  static Content con;



    @Override
    public void create () {
        Gdx.input.setInputProcessor(new GameInputProcessor());
        con=new Content();
        con.loadTexture("images//sprite.jpg","sprite");
        con.loadTexture("images//background.png","background");

        gsm=new GameStateManager(this);

        sb=new SpriteBatch();
        cam=new OrthographicCamera(160,120);


        cam.setToOrtho(false,Width/2,Height/2);
        hud=new OrthographicCamera();
        hud.setToOrtho(false,Width/2,Height/2);










    }

    @Override
    public void render () {
        cam.update();
        hud.update();

        accumulator +=Gdx.graphics.getDeltaTime();
        while(accumulator>=STEP){
            accumulator-=STEP;
            gsm.update(STEP);
            gsm.render();
            MyInput.update();
        }



    }
    public void resize(int width,int height){
        sb.getProjectionMatrix().setToOrtho2D(0, 0, width, height);
     }

    public void dispose(){
            con.disposeTexture("sprite");
            con.disposeTexture("background");
    }
    public void pause(){

    }

    public void resume(){
        gsm.setState(GameStateManager.PLAY);
    }
}

我已将纹理加载到MyMainClass.java中,并将其存储在Content类的HashMap中 我将名为“ back”的背景图像获取为Texture,并在Play类的Play构造函数中将其分离为TextureRegions天空,云朵和山脉,并在Background类中传递它们。

package com.mygdx.gamestate;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.mygdx.game.MyMainGame;
import com.mygdx.manager.GameStateManager;

public abstract class GameState {

    protected GameStateManager gsm;
    protected MyMainGame game;
    protected SpriteBatch sb;
    protected OrthographicCamera cam;
    protected OrthographicCamera hud;

    protected GameState(GameStateManager gsm){
        this.gsm=gsm;
        game=gsm.game();
        sb=game.getSb();
        cam=game.getCam();
        hud=game.getHud();
        init();

    }

    public abstract void init();
    public abstract void update(float dt);
    public abstract void draw();
    public abstract void render();
    public abstract void handleInput();
    public abstract void dispose();



}

背景类

public class Play extends GameState{

  //  private BitmapFont font=new BitmapFont();
    private World  world;
    private Body playerBody;
    private int viewportWidth= 10 * 32 ;
    int viewportHeight= 8 * 32 ;


    private Box2DDebugRenderer b2d;
    private OrthographicCamera B2DCAM;
    private TiledMap tileMap;
    private OrthogonalTiledMapRenderer orthomap;
    private MyContactListener cl;
    private float tileSize;
    private Background[] backgrounds;
    private Texture back;



    //file name
    private final String LEVEL_1 ="maps/tilemap1.tmx";

    public Play(GameStateManager gsm) {
        super(gsm);


        //setup box2d
        world=new World(new Vector2(0,-9.8f),true);
        cl=new MyContactListener();
        world.setContactListener(cl);
         sb=new SpriteBatch(1000);
        //cam=new OrthographicCamera();

        b2d=new Box2DDebugRenderer();

        //create Player
        createPlayer();
        //create Tiles
        createTiles();
        orthomap = new OrthogonalTiledMapRenderer(tileMap,1/32f);



        //setup Box2D Cam
        B2DCAM=new OrthographicCamera();
        B2DCAM.setToOrtho(false, MyMainGame.Width/PPM,MyMainGame.Height/PPM);
        cam=new OrthographicCamera();
        cam.setToOrtho(false,10,7);


         back = MyMainGame.con.getTexture("background");



      TextureRegion sky = new TextureRegion(back, 0, 0, 320, 240);
       TextureRegion clouds = new TextureRegion(back, 0, 240, 320, 240);
       TextureRegion mountains = new TextureRegion(back, 0, 480, 320, 240);
        backgrounds = new Background[3];
       backgrounds[0] = new Background(sky,cam, 0f);
       backgrounds[1] = new Background(clouds, cam, 0.1f);
       backgrounds[2] = new Background(mountains, cam, 0.2f);







      /* //TODO - remove me
        File file = new File(LEVEL_1);
        if(file.exists())
            System.out.println("file exists");*/


    }


    @Override
    public void init() {

    }

    @Override
    public void update(float dt) {
        handleInput();
            world.step(dt,6,2);
            MyMainGame.con.getTexture("sprite");

        for (Background b : backgrounds) {
          b.update(dt);
        }
    }

    @Override
    public void draw() {

    }

    @Override
    public void render() {

        //clear screen

        Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);
      //
        cam.position.set(playerBody.getPosition().x * PPM +MyMainGame.Width / 4,MyMainGame.Height / 2,0);
        // cam.setToOrtho(false,playerBody.getPosition().x * PPM +MyMainGame.Width / 4,MyMainGame.Height / 2);
        //cam.setPosition(playerBody.getPosition().x * PPM +MyMainGame.Width / 4, MyMainGame.Height / 2);

        cam.setToOrtho(false,10,7);

       cam.update();





        sb.setProjectionMatrix(cam.combined);
        for(int i = 0; i < backgrounds.length; i++) {
            backgrounds[i].render(sb);
       }


        orthomap.setView(cam);
        orthomap.render();
        b2d.render(world,B2DCAM.combined);




    }

    @Override
    public void handleInput() {
     if(MyInput.isPressed((MyInput.SPACE))){
         System.out.println("space pressed");
         if(cl.isPlayerOnGround())
             System.out.println(cl.isPlayerOnGround());
             playerBody.applyForceToCenter(0,200,true);
         }
     }


    @Override
    public void dispose() {
        world.dispose();
        b2d.dispose();
        tileMap.dispose();
        orthomap.dispose();
    }

    private void createPlayer(){
        BodyDef bodydef=new BodyDef();
        FixtureDef fixdef=new FixtureDef();
        PolygonShape shape=new PolygonShape();


        //create player
        bodydef.position.set(160/PPM,200/PPM);
        bodydef.type= BodyDef.BodyType.DynamicBody;
        playerBody=world.createBody(bodydef);

        shape.setAsBox(5/PPM,5/PPM);
        fixdef.shape=shape;
        fixdef.filter.categoryBits= BIT_PLAYER;
        fixdef.filter.maskBits=Box2DVariables.BIT_BLUE;
        playerBody.createFixture(fixdef).setUserData("PLAYER");


        //create foot sensor
        shape.setAsBox(2/PPM,2/PPM,new Vector2(0,-5/PPM),0);
        fixdef.shape=shape;
        fixdef.filter.categoryBits= BIT_PLAYER;
        fixdef.filter.maskBits=Box2DVariables.BIT_BLUE;
        fixdef.isSensor=true;
        playerBody.createFixture(fixdef).setUserData("FOOT");
    }
    private void createTiles(){
//load tile map
        tileMap = new TmxMapLoader().load(LEVEL_1);
        //orthomap = new OrthogonalTiledMapRenderer(tileMap,1);


        tileSize=(int)tileMap.getProperties().get("tilewidth", Integer.class);
        System.out.println("Tile Size " +tileSize);

        TiledMapTileLayer layer;

        layer=(TiledMapTileLayer)tileMap.getLayers().get("Blue");
            createLayer(layer,Box2DVariables.BIT_BLUE);
        layer=(TiledMapTileLayer)tileMap.getLayers().get("Green");
        createLayer(layer,Box2DVariables.BIT_GREEN);
        layer=(TiledMapTileLayer)tileMap.getLayers().get("Red");
        createLayer(layer,Box2DVariables.BIT_RED);
        System.out.println("Layer Height " +layer.getHeight());
        System.out.println("Layer Width " +layer.getWidth());
    }
    private void createLayer(TiledMapTileLayer layer,short bits){
        BodyDef bodydef=new BodyDef();
        FixtureDef fixdef=new FixtureDef();

//go through cells in layer
        for(int row=0;row<layer.getHeight();row++){
            for(int col=0;col<layer.getWidth();col++){
                //get cells
                TiledMapTileLayer.Cell cell=layer.getCell(col,row);

                //check if cell exists
                if(cell==null) continue;
                if(cell.getTile()==null) continue;

                //create body and fixture from cell
                bodydef.type= BodyDef.BodyType.StaticBody;
                bodydef.position.set((col+0.5f)*tileSize/PPM,(row+0.5f)*tileSize/PPM);
                ChainShape cs=new ChainShape();
                Vector2[] v=new Vector2[3];
                //bottom left
                v[0]=new Vector2(-tileSize/2/PPM,-tileSize/2/PPM);
                //top left
                v[1]=new Vector2(-tileSize/2/PPM,tileSize/2/PPM);
                //top right corner
                v[2]=new Vector2(tileSize/2/PPM,tileSize/2/PPM);


                cs.createChain(v);
                fixdef.friction=0;
                fixdef.shape =cs;
                fixdef.filter.categoryBits=Box2DVariables.BIT_BLUE;
                fixdef.filter.maskBits=BIT_PLAYER;
                fixdef.isSensor=false;
                world.createBody(bodydef).createFixture(fixdef);

            }
        }
    }
}

我在渲染方法的Play类中收到一个错误,作为空指针异常。真的不知道发生了什么! sb.setProjectionMatrix提供nullpointer异常!

TextureRegion sky = new TextureRegion(back, 0, 0, 320, 240);
       TextureRegion clouds = new TextureRegion(back, 0, 240, 320, 240);
       TextureRegion mountains = new TextureRegion(back, 0, 480, 320, 240);
        backgrounds = new Background[3];
       backgrounds[0] = new Background(sky,cam, 0f);
       backgrounds[1] = new Background(clouds, cam, 0.1f);
       backgrounds[2] = new Background(mountains, cam, 0.2f);

如何分割背景图像并按照上面在游戏中所示添加它?

0 个答案:

没有答案