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

2015/5/4

Making items appear after certain amount of time

Programmer1998 Programmer1998

2015/5/4

#
Trying to get my coins to appear for a certain amount of time if my player touches a red coin. However I can not seem to get the coins to appear once my player touches a red coin at the moment. Here is my code: Coin class:
public class Coin extends Items implements Appearance
{
    private int appearCounter_;
    public Coin()
    {
        super();
        appearCounter_ = 0;
    }
    
    /**
     * Act - do whatever the Coin wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        super.act();
        World w = getWorld();
        if(appearCounter_ > 0)
        {
            w.addObject(this, 500, 350);
            appearCounter_ --;
        }
        else if(appearCounter_ <= 0)
        {
            w.removeObject(this);
        }
    }    

    public void appear(int count)
    {
        appearCounter_ = count;
    }
}
Player class:
  public void act() 
    {
        // Add your action code here.
        super.act();
        if(isTouching(RedCoin.class))
        {
            World w = getWorld();
            RedCoin rCoin = (RedCoin)getOneIntersectingObject(RedCoin.class);
            w.removeObject(rCoin);
            appearItems();
        }
    }    

public void appearItems()
    {
        List<Appearance> appear = getWorld().getObjects(Appearance.class);
        ListIterator<Appearance> appearIter = appear.listIterator();
        while(appearIter.hasNext())
        {
            Appearance a = appearIter.next();
            a.appear(450);
        }
    }
and my Interface:
public interface Appearance
{
    public void appear(int count);
}
yedefei yedefei

2015/5/4

#
You should first add an object into the world and then invoke its act() method , so "w.addObject(this, 500, 350);" can't work .
danpost danpost

2015/5/4

#
What yedefei said about the statement not working is true. There is another point to consider about the statement, however. If the object was not yet in the world, then 'w', which is assigned the value returned by 'getWorld' will be 'null'. It is rare, and should be avoided, to have an actor add itself into a world. For one thing, it would need to know what world object to add itself into. For another, it would need to know where in that world to add itself. These parameters should come from outside sources -- like the world, or an actor in that world.
You need to login to post a reply.