Hello,
I'm making a car game where the player's car tries to dodge oncoming traffic. When the traffic reaches the bottom of the world, and if it didn't touch the player car, points are added. However, I'm receiving a null pointer exception and I'm not sure why and how to fix this. Can someone please help? Thank you.
Here's the code for the Vehicle class (the traffic):
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Randomly has trucks spawn that drive down the road, will not let two trucks spawn on top of eachother
* also truck will explode if it hits a laser.
* @author Hubert Jackson Black III
* @version v0.10
*/
public class Vehicle extends Actor
{
private CarWorld world;
private Score scTxt;
public void act(){
checkCollision();
driveDown();
endOfRoad();
}
public void driveDown() // moves trucks down the screen at 3 units.
{
setLocation(getX(), getY() + 3);
}
public void checkCollision() // checks if the trucks spawn on top of eachother. will remove one.
{
Actor truck = getOneIntersectingObject(Vehicle.class);
if(truck != null)
{
getWorld().removeObject(truck);
}
}
public void endOfRoad() // removes truck once it hits end of the world.
{
if(getY() >= getWorld().getHeight() -1)
{
if (getOneIntersectingObject(PlayerCar.class) == null){
world.setScore(world.getScore() + 1);
scTxt.setText("Score: " + world.getScore());
}
getWorld().removeObject(this);
}
}
protected void addedToWorld(CarWorld w){
world = (CarWorld)w;
scTxt = world.getObjects(Score.class).get(0);
}
}
Here's the exception:
java.lang.NullPointerException
at Vehicle.endOfRoad(Vehicle.java:39)
at Vehicle.act(Vehicle.java:16)
at greenfoot.core.Simulation.actActor(Simulation.java:567)
at greenfoot.core.Simulation.runOneLoop(Simulation.java:530)
at greenfoot.core.Simulation.runContent(Simulation.java:193)
at greenfoot.core.Simulation.run(Simulation.java:183)

