hello everybody!
I am trying to make a magnet working with a button, but I can't spawn the gravitybeam because it is not in the world yet.
I thought that just placing one out of view and then moving it to the magnet when I wanted it to would fix the problem, but when I try to move it it wont work, and when I move it by stopping the scenario, rightclicking the button and clicking spawn, it gives me this error:
"java.lang.NullPointerException
at Magnet.spawn(Magnet.java:13)
at Knop.spawn(Knop.java:40)
"
here's my code.
I am not good with references so please awnser in lamens terms.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class Knop extends Scroll
{
public int counter = 0;
public void act()
{
move(7);
}
public boolean isUmanNear()
{
if(!getObjectsInRange(40, Uman.class).isEmpty())
{
return true;
}
else {
return false;
}
}
public boolean isXPressed()
{
if(Greenfoot.isKeyDown("x"))
{
return true;
}
else {
return false;
}
}
public void spawn()
{
if(isUmanNear() || isXPressed())
{
Level1 level1 = (Level1) getWorld();
Magnet magnet = level1.getMagnet();
magnet.spawn();
}
}
} import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class Magnet extends Scroll
{
public void act()
{
move(7);
}
public void spawn()
{
Level1 level1 = (Level1) getWorld();
GravityUp gu = level1.getGravityUp();
gu.spawn();
}
} import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class achtergrond here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Level1 extends World
{
private Magnet mag;
private GravityUp gu;
/**
* Constructor for objects of class achtergrond.
*
*/
public Level1()
{
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(600, 400, 1, false);
prepare();
setPaintOrder(ZwarteBalk.class);
mag = new Magnet();
gu = new GravityUp();
}
public GravityUp getGravityUp()
{
return gu;
}
public Magnet getMagnet()
{
return mag;
}
public void prepare()
{ GravityUp gu = new GravityUp();
addObject(gu, 0, 10000);
}
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class GravityUp here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class GravityUp extends Scroll
{
/**
* Act - do whatever the groundblock wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
move(7);
}
public void spawn()
{
Level1 level1 = (Level1) getWorld();
GravityUp gu = level1.getGravityUp();
setLocation(getX(), getY());
}
}
