-4

I am getting a NullPointerException for no reason. Please don't redirect me to another post. I have looked at all of them. I am making a game with LibGDX.

Here is the Error

Exception in thread "LWJGL Application" java.lang.NullPointerException
    at net.hasanbilal.pr.entities.Entity.getWeight(Entity.java:88)
    at net.hasanbilal.pr.entities.Entity.update(Entity.java:25)
    at net.hasanbilal.pr.entities.Porter.update(Porter.java:34)
    at net.hasanbilal.pr.world.GMap.update(GMap.java:28)
    at net.hasanbilal.pr.world.TiledGMap.update(TiledGMap.java:40)
    at net.hasanbilal.pr.PrisonRevelations.render(PrisonRevelations.java:59)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)

I will be showing each class that the error points too.

This is the Entity Class.

package net.hasanbilal.pr.entities;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;

import net.hasanbilal.pr.world.GMap;

public abstract class Entity {

    protected Vector2 pos;
    protected EntityType t;
    protected float velocityY = 0;
    protected GMap m;
    protected boolean grounded = false;

    public void create (EntitySnapshot snapshot, EntityType type, GMap map) {
        this.pos = new Vector2(snapshot.getX(),snapshot.getY());
        this.t = t;
        this.m = m;
    }

    public void update (float delta, float g) {
        float newY = pos.y;

        this.velocityY += g * delta * getWeight();
        newY += this.velocityY * delta;

        if (m.doesRectCollideWithMap(pos.x, newY, getWidth(), getHeight())) {
            if (velocityY < 0) {
                this.pos.y = (float) Math.floor(pos.y);
                grounded = true;
            }
            this.velocityY = 0;
        } else {
            this.pos.y = newY;
            grounded = false;
        }


    }

    public abstract void render (SpriteBatch b);


    protected void moveX(float amount) {
        float newX = this.pos.x + amount;
        if (!m.doesRectCollideWithMap(newX, pos.y, getWidth(), getHeight()))
            this.pos.x = newX;
    }

    public EntitySnapshot getSaveSnapshot(){
        return new EntitySnapshot(t.getId(), pos.x, pos.y);
    }

    public Vector2 getPos() {
        return pos;
    }

    public float getX() {
        return pos.x;
    }

    public float getY() {
        return pos.y;
    }

    public EntityType getT() {
        return t;
    }

    public float getVelocityY() {
        return velocityY;
    }

    public boolean isGrounded() {
        return grounded;
    }

    public int getWidth() {
        return t.getWidth();
    }

    public int getHeight() {
        return t.getHeight();
    }

    public float getWeight() {
        return t.getWeight();
    }


}

This is the Porter Class.

package net.hasanbilal.pr.entities;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

import net.hasanbilal.pr.world.GMap;

public class Porter extends Entity {

    private static final int SPEED = 80;
    private static final int JUMP_VELOCITY = 5;
    Texture img;

    public void create (EntitySnapshot snapshot, EntityType type, GMap map) {
        super.create(snapshot, type, map);
        img = new Texture("porter.png");

    }

    @Override
    public void render(SpriteBatch b) {
        b.draw(img, pos.x, pos.y, getWidth(), getHeight());

    }

    public void update(float delta, float g) {
        if (Gdx.input.isKeyPressed(Keys.SPACE) && grounded)
            this.velocityY += JUMP_VELOCITY * getWeight();
        else if (Gdx.input.isKeyPressed(Keys.SPACE) && !grounded && this.velocityY > 0)
            this.velocityY += JUMP_VELOCITY * getWeight() * delta;

        super.update(delta, g);

        if (Gdx.input.isKeyPressed(Keys.LEFT))
            moveX(-SPEED * delta);

        if (Gdx.input.isKeyPressed(Keys.RIGHT))
            moveX(SPEED * delta);
    }


}

This is the GMap

package net.hasanbilal.pr.world;

import java.util.ArrayList;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

import net.hasanbilal.pr.entities.Entity;
import net.hasanbilal.pr.entities.EntityLoader;
import net.hasanbilal.pr.entities.Porter;

public abstract class GMap {

    protected ArrayList<Entity> entities;

    public GMap() {
        entities = new ArrayList<Entity>();
        entities.addAll(EntityLoader.loadEntities("basic", this, entities));
    }

    public void render (OrthographicCamera c, SpriteBatch b) {
        for (Entity entity : entities) {
            entity.render(b);
        }
    }
    public void update (float deltaTime) {
        for (Entity entity : entities) {
            entity.update(deltaTime, -9.8f);
        }
    }
    public void dispose () {
        EntityLoader.saveEntities("basic", entities);
    }

    /**
     * Gets a tile by location
     * @param layer
     * @param x
     * @param y
     * @return
     */
    public TileType getByLocation(int layer, float x, float y) {
        return this.getByCoordinate(layer, (int) (x / TileType.TILE_SIZE), (int) (y / TileType.TILE_SIZE));
    }

    /**
     * Gets Tile by coordinate
     * @param layer
     * @param col
     * @param row
     * @return
     */
    public abstract TileType getByCoordinate(int layer, int col, int row);

    public boolean doesRectCollideWithMap(float x, float y, int width, int height) {
        if (x<0 || y < 0 || x + width > getPixelWidth() || y + height > getPixelHeight())
            return true;

        for (int row = (int) (y / TileType.TILE_SIZE); row < Math.ceil((y + height) / TileType.TILE_SIZE); row++) {
            for (int col = (int) (x / TileType.TILE_SIZE); col < Math.ceil((x + width) / TileType.TILE_SIZE); col++) {
                for (int layer = 0; layer < getLayers(); layer++) {
                    TileType type = getByCoordinate(layer, col, row);
                    if (type != null && type.isCollidable())
                        return true;
                }
            }
        }
        return false;
    }

    public abstract int getWidth();
    public abstract int getHeight();
    public abstract int getLayers();

    public int getPixelWidth() {
        return this.getWidth() * TileType.TILE_SIZE;
    }

    public int getPixelHeight() {
        return this.getHeight() * TileType.TILE_SIZE;
    }

}

This is the class for the TiledGMap

package net.hasanbilal.pr.world;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTile;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;

import net.hasanbilal.pr.entities.Entity;
import net.hasanbilal.pr.entities.Porter;

public class TiledGMap extends GMap {

    TiledMap lvl1;
    OrthogonalTiledMapRenderer otmr;

    public TiledGMap() {
        lvl1 = new TmxMapLoader().load("level1.tmx");
        otmr = new OrthogonalTiledMapRenderer(lvl1);
    }


    @Override
    public void render(OrthographicCamera c, SpriteBatch b) {
        otmr.setView(c);
        otmr.render();

        b.setProjectionMatrix(c.combined);
        b.begin();
        super.render(c, b);
        b.end();

    }

    @Override
    public void update(float deltaTime) {
        super.update(deltaTime);

    }

    @Override
    public void dispose() {
        lvl1.dispose();

    }

    @Override
    public TileType getByCoordinate(int layer, int col, int row) {
        Cell cell  = ((TiledMapTileLayer) lvl1.getLayers().get(layer)).getCell(col, row);

        if (cell !=null) {
            TiledMapTile t = cell.getTile();

            if (t != null) {
                int id = t.getId();
                return TileType.getTileTypeById(id);
            }
        }
        return null;
    }

    @Override
    public int getWidth() {

        return ((TiledMapTileLayer) lvl1.getLayers().get(0)).getWidth();
    }

    @Override
    public int getHeight() {

        return ((TiledMapTileLayer) lvl1.getLayers().get(0)).getHeight();
    }

    @Override
    public int getLayers() {

        return lvl1.getLayers().getCount();
    }

}

This is the Prison Revelations class

package net.hasanbilal.pr;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;

import net.hasanbilal.pr.world.GMap;
import net.hasanbilal.pr.world.TileType;
import net.hasanbilal.pr.world.TiledGMap;

public class PrisonRevelations extends ApplicationAdapter {

    OrthographicCamera c;
    SpriteBatch b;

    GMap gm;

    @Override

    public void create () {
        b = new SpriteBatch();

        c = new OrthographicCamera();
        c.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        c.update();
        gm = new TiledGMap();



    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(255, 255, 255, 1);
        Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);



        if (Gdx.input.isTouched()) {
            c.translate(-Gdx.input.getDeltaX(), Gdx.input.getDeltaY());
            c.update();
        }

        if (Gdx.input.justTouched()) {
            Vector3 pos = c.unproject(new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0));
            TileType t = gm.getByLocation(1, pos.x, pos.y);

            if (t != null) {
                System.out.println("You clicked on tile with id" + t.getId() + " " + t.getName()+ " " + t.isCollidable() + " " + t.getDamage());
            }
        }

        c.update();
        gm.update(Gdx.graphics.getDeltaTime());
        gm.render(c, b);
    }

    @Override
    public void dispose () {
        b.dispose();
        gm.dispose();
    }
}

Please help. Im gonna die. This is due soon.

Nexevis
  • 4,647
  • 3
  • 13
  • 22
John Bob
  • 77
  • 7
  • 6
    Did you try using a debugger to understand why you are actually having a NullPointerException? Try it out if not! – D. Lawrence Jan 16 '20 at 15:45
  • ... what do you mean by "this is due soon" ? – Shark Jan 16 '20 at 15:46
  • 1
    *Getting `NullPointerException` for `null` reason* would fit a lot better... What `t` and `m` are you exactly setting in the `create` method? I cannot see any arguments named like that so you might be initializing them both with themselves (`null`) and then get the mentioned result when calling `getWeight()`. – deHaar Jan 16 '20 at 15:47
  • 5
    NullPointerException don't happen for no reason. They always happen for the exact same reason and this is why no matter how much you protest that your question is not a duplicate it still is one. – OH GOD SPIDERS Jan 16 '20 at 15:48
  • usually the reason for getting a NullPointerException is operating on null. In your case t seems to be null. – Nicktar Jan 16 '20 at 15:48
  • 6
    Look at your `create` method in `Entity`... `public void create (EntitySnapshot snapshot, EntityType type, GMap map) { this.pos = new Vector2(snapshot.getX(),snapshot.getY()); this.t = t; this.m = m; }` you set `t` and `m` to itself, because you're not providing any values from outside. And the default value for objects is `null` – QBrute Jan 16 '20 at 15:48
  • 1
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Nexevis Jan 16 '20 at 15:50
  • @D.Lawrence Yeah, but I think I did it wrong. It gave me no info. – John Bob Jan 16 '20 at 15:52
  • @Shark It is a school assignmnet – John Bob Jan 16 '20 at 15:52

1 Answers1

6

Looks like you made a mistake with parameters names on your create, change to this:

public void create (EntitySnapshot snapshot, EntityType type, GMap map) {
    this.pos = new Vector2(snapshot.getX(),snapshot.getY());
    this.t = type;
    this.m = map;
}
  • 3
    @JohnBob: most importantly, learn how to find it: See how it says `Entity.getWeight` in the stack trace? Check the code of that method and ask yourself "what value could *possibly* be `null` in that method". The answer is that there's only one value that's dereferenced and that is `t`. From there find out why `t` is `null`. – Joachim Sauer Jan 16 '20 at 16:00
  • @JoachimSauer sure thanks bro – John Bob Jan 16 '20 at 16:02
  • @John Bob I also recommend looking over your Error/Warning settings on your IDE, because this is something that my IDE warns me about because I changed a lot of the settings to give warnings rather than not say anything. It is better, in my opinion, to have too many warnings and then decrease the ones you don't need, rather than have not enough warnings. (My Eclipse highlights it and says this assignment has no effect). – Nexevis Jan 16 '20 at 16:11