I am making a game, where a space ship shoots an enemy.
If you follow my code, the enemy should have 3 health.
I can compile the world, but once i shoot the enemy i get this error code:
java.lang.IllegalStateException: Actor not in world. An attempt was made to use the actor's location while it is not in the world. Either it has not yet been inserted, or it has been removed.
at greenfoot.Actor.failIfNotInWorld(Actor.java:681)
at greenfoot.Actor.getX(Actor.java:157)
at Mover.atWorldEdge(Mover.java:70)
at Bullet.act(Bullet.java:19)
at greenfoot.core.Simulation.actActor(Simulation.java:583)
at greenfoot.core.Simulation.runOneLoop(Simulation.java:541)
at greenfoot.core.Simulation.runContent(Simulation.java:215)
at greenfoot.core.Simulation.run(Simulation.java:205)
Heres the code for the Bullet:
And here's the code for the enemy
Code for spaceship:
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Bullet here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Bullet extends Mover
{
/**
* Act - do whatever the Bullet wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
move(10.0);
hitEnemy();
if (this.atWorldEdge())
{
getWorld().removeObject(this);
}
}
public void hitEnemy() {
Enemy enemy = (Enemy) getOneObjectAtOffset(0, 0, Enemy.class);
if (enemy != null) {
enemy.setHealth(-1);
getWorld().removeObject(this);
}
}
}
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Enemy1 here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Enemy extends Actor
{
/**
* Act - do whatever the Enemy1 wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
}
private int health = 5;
public void setHealth(int points) {
health += points;
}
public int getHealth() {
return health;
}
}
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class Spaceship extends Actor
{
/**
* Act - do whatever the Crab wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
private float fireTimer;
public void act()
{
moveAndTurn();
eat();
if ("space".equals(Greenfoot.getKey()))
{
{
fire1();
fire2();
}
}
}
public void moveAndTurn()
{
move (0);
if (Greenfoot.isKeyDown("down"))
{
setLocation(getX(), getY()+5);
}
if (Greenfoot.isKeyDown("up"))
{
setLocation(getX(), getY()-5);
}
if (Greenfoot.isKeyDown("right"))
{
move(5);
}
if (Greenfoot.isKeyDown("left"))
{
move(-5);
}
}
public void eat()
{
}
private void fire1()
{
{
Bullet bullet = new Bullet();
getWorld().addObject(bullet, getX(), getY()+52);
}
}
private void fire2()
{
{
Bullet bullet = new Bullet();
getWorld().addObject(bullet, getX(), getY()-52);
}
}
}


