This site requires JavaScript, please enable it in your browser!
Greenfoot back
Confringo
Confringo wrote ...

2017/10/24

Add object

Confringo Confringo

2017/10/24

#
Hello, I'm trying to create an object whenever I press the space key, but I keep on getting an error in the terminal window saying "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." My main issue is that the object isn't being created whenever it should be, instead the program stops working. Here is my code (please help improve it so I can fix my issue): import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class Spaceship1 extends Actor { World world= getWorld(); public void shoot() { //Space1 x = new Space1(); if (Greenfoot.isKeyDown("space")==true){ Spaceship1 x = new Spaceship1(); world.addObject(new lazer(), x.getX(), x.getY()); } else { Spaceship1 x = new Spaceship1(); //world.addObject(new lazer(), x.getX(), x.getY()); } //addObject(new lazer(), x.getX(), x.getY()); } public void act() { // Add your action code here. shoot(); checkKeyPress(); } } thanks!
danpost danpost

2017/10/25

#
Remove the line that is causing the error:
World world = getWorld();
You cannot execute that method until the Spaceship1 object is created and added into a world. Where you have the line, it is executed while the object is being created and before it is added into a world. Change all remaining 'world' in your code to 'getWorld()'. The only thing that should be new in the class are lazer objects. When the 'act' method is executed, which executes the 'shoot' and 'checkKeyPress' (missing from given code) methods, a Spaceship1 object exists and is in a world. You do not want to create another Space1 world object or another Spaceship1 actor object. Remove all lines with the world 'new' in them except for the 'new lazer' line. Change all 'x' in what is remaining to 'this' or you can simply remove them along with the dots that follow them.
You need to login to post a reply.