In the grid world case study foe my final project I am making a game. In the game if the player clicks the "W" key the shiftUp() method is called which makes all of the other actors of a certain instance move down to create the illusion of the player moving. This isn't a finished implementation of the method but this should get all the actors in the grid and test if they are an instance of a class called Enemy which extends Actor. If so the actor should move up one space. When I call this method a NullPointerException is called on the line that calls enemy.moveTo(...); This shouldn't happen because I check to see if it's null. Can anyone help me with this? I get this: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
public void shiftUp()
{
if (((GameGrid)getGrid()).getMinX() != 0)
{
Grid<Actor> grid = getGrid();
if (grid != null)
{
for (int y = 0; y < getGrid().getNumRows(); y++)
for (int x = 0; x < getGrid().getNumCols(); x++)
{
Actor enemy = grid.get(new Location(y,x));
if (enemy != null && enemy instanceof Enemy)
enemy.moveTo(new Location(enemy.getLocation().getRow() - 1, enemy.getLocation().getCol()));
}
}
}
}
Since you are checking for enemy != null
beforehand, I'm guessing that enemy.getLocation()
is returning null
, which is causing a NullPointerException
when you call null.getRow()
and null.getCol()
.
If this is the case, then it looks like the problem is that your Actor
is never given a proper Location
in the grid. Make sure you are using the putSelfInGrid(Grid<Actor> grid, Location loc)
method to place the Actor
in the grid (not grid.put(Location loc, E obj)
), as putSelfInGrid()
sets your Actor
's location accordingly.