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

2011/12/29

Broadcast?

toytttttt toytttttt

2011/12/29

#
Can one object tell other objects in a world to do a certain action? I've seen programs that must use this, but I cant seem to do it. Any help?
DonaldDuck DonaldDuck

2011/12/29

#
A simple way to do this is to have a boolean(or integer) defined in your world class and check if it's true from a different object.
public class myWorld extends World
{
    public boolean hasToRun = false;

    public void act()
    {
        System.out.println("hasToRun is " + hasToRun);
    }
}
public class actor extends Actor
{
    protected void addedToWorld(World world)
    {
        // When this is added to the world, assign hasToRun in myWorld to true.
        ((myWorld) getWorld()).hasToRun = true;
    }
}
This code should print false to the terminal until the actor is added to the world.
toytttttt toytttttt

2011/12/29

#
Thanks, I'll give it a try!
toytttttt toytttttt

2011/12/30

#
Question; if I wanted this to be if the actor leaves world print true, how would I change it?
DonaldDuck DonaldDuck

2011/12/31

#
In the actor,
public void die()
{
    ((myWorld) getWorld()).hasToRun = false;
    getWorld().removeObject(this);
}
In the world class, at the top,
import java.util.List;
import java.util.Iterator;
Also in the world
private void removeActor()
{
    List l = getWorld().getObjects(actor.class);
    Iterator i = l.iterator();
    while(i.hasNext())
    {
        Actor a = (Actor)i.next();
        if(a.instanceof actor)
        {
            ((actor)a).die();
        }
    }
}
    
And add this to the world
public void act()
{
    if(MEETS_PARAMS_TO_REMOVE_ACTOR)
    {
        removeActor();
    }
}
This works provided there is only 1 actor in the world. You can put this in other actor classes too. An easy way to do this is to set the Boolean to false in the world when you remove the object(wherever the removeObject occurs)
danpost danpost

2011/12/31

#
Another way (provided there is only one actor in the world): In the world class: add the second line to line 1 below
public boolean actorNotHere = true;
public actor myActor = new actor();
Then, use 'myActor' with addObject and removeObject to add and remove the actor to and from the world. Finally, in the world act() method, add this one line
actorNotHere = getObjects(actor.class).size() == 0; // keeping the value of 'actorNotHere' current
You will only need to add to the top of the world class:
import java.util.List;
Now, you can check on the value of 'actorNotHere' from just about anywhere.
toytttttt toytttttt

2011/12/31

#
Thanks for all the help!
You need to login to post a reply.