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

2015/6/18

Why cant I get world information inside an Actor constructor?

jguevar3 jguevar3

2015/6/18

#
I am trying to get the height and with of the world inside an actor constructor but it won't let me. HEre is my code:
public class Alligator extends Actor
{

    int worldWidth;
    
    public Alligator()
    {    
      System.out.println("Alligator created");
      worldWidth = getWorld().getWidth();
      
    }
    
miningmanna miningmanna

2015/6/18

#
you cant get the world, when the Actor isnt in the world yet What i use to do is to add an argument
public Aligator(World world) { worldWidth = world.getWidth() }
miningmanna miningmanna

2015/6/18

#
ups forgot the semicolon
danpost danpost

2015/6/18

#
You could also make use of the 'addedToWorld(World)' method of the Actor class. The method is empty by default and called automatically when an actor is added into any world.
protected void addedToWorld(World world) { worldWidth = world.getWidth(); }
Using this would be better than passing the world to the constructor, as when doing so, if the actor was added into another world of a different size, the value of the field would not be accurate. However, there is little need for the 'worldWidth' field as 'getWorld().getWidth()' could replace any occurrences of the field in the main code, always returning an accurate value.
jguevar3 jguevar3

2015/6/18

#
Thank you guys! I ended up using the addedToWorld() method like this:
protected void addedToWorld(World See)
    {
        worldWidth = getWorld().getWidth();
        System.out.println("Alligator added to the world");
        
    }
I
You need to login to post a reply.