Well at first it did quite weird when I tried to let the world make the turret so I thought lets let the tank make the turret. But I already know a solution to that problem to work this crapy code out
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class MainWorld here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class MainWorld extends World
{
/**
* Constructor for objects of class MainWorld.
*
*/
public MainWorld()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(600, 400, 1);
TankTurret turret = new TankTurret();
TankBase tank = new TankBase(turret);
addObject(tank, 200, 200);
addObject(turret, 198, 199);
}
}
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class TankTurret here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class TankTurret extends Actor
{
/**
* Creates the Turret and makes sure everything is all right.
*/
public TankTurret()
{
}
/**
* Act - do whatever the TankTurret wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
turn();
followTank();
}
/**
* Turn towards mouse.
*/
public void turn()
{
if (Greenfoot.getMouseInfo() == null)
{
}
else
{
MouseInfo mouse = Greenfoot.getMouseInfo();
turnTowards((int)mouse.getX(), (int)mouse.getY());
}
}
/**
* Takes care of the staying togheter of the tank and the Turret.
*/
public void followTank()
{
}
public void setLocation()
{
}
}import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class TankBase here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class TankBase extends Actor
{
TankTurret turret;
/**
* Creates the Tank and makes sure everything is all right.
*/
public TankBase(TankTurret tankTurret)
{
this.turret = turret;
}
/**
* Does what the tank does.
*/
public void act()
{
drive();
}
/**
* Lets the Tank move with the WASD-keys.
*/
private void drive()
{
if (Greenfoot.isKeyDown("w"))
{
move(5);
turret.setLocation(getX(), getY());
}
if (Greenfoot.isKeyDown("s"))
{
move(-5);
turret.setLocation(getX(), getY());
}
if (Greenfoot.isKeyDown("a"))
{
if(Greenfoot.isKeyDown("s"))
{
turn(4);
}
else
{
turn(-4);
}
}
if (Greenfoot.isKeyDown("d"))
{
if(Greenfoot.isKeyDown("s"))
{
turn(-4);
}
else
{
turn(4);
}
}
}
}
java.lang.NullPointerException at TankBase.drive(TankBase.java:37) at TankBase.act(TankBase.java:26) at greenfoot.core.Simulation.actActor(Simulation.java:568) at greenfoot.core.Simulation.runOneLoop(Simulation.java:526) at greenfoot.core.Simulation.runContent(Simulation.java:215) at greenfoot.core.Simulation.run(Simulation.java:205)