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

2014/2/6

How to press & repress a lever

BGY12C BGY12C

2014/2/6

#
Hey, I want to make an object disappear when I walk past a lever. But it the object has to appear again when I'm away from the lever. Apart from that how does the methode "delay" work? How do I use this methode without freezing the whole game for a moment.
    public int status = 1;
    
    public void act() 
    {
        falle();
    }   
    
    public boolean schalterAktiviert(){
        Actor unter = getOneObjectAtOffset(0, getImage().getHeight(), Siggi.class);
        return unter != null;    
    }
    
    public void falle(){
           if(schalterAktiviert() && status == 1){
               getWorld().removeObjects(getWorld().getObjects(FalleZacken.class)); 
               status = 2;
               Greenfoot.delay(100);
           }
           else if (schalterAktiviert() && status == 2){
                getWorld().addObject(new FalleZacken(), 400, 510); 
                status = 1;
           }
    }
Schalter = lever Thanks ;)
davmac davmac

2014/2/6

#
Apart from that how does the methode "delay" work?
It delays execution for the specified time.
How do I use this methode without freezing the whole game for a moment.
You can't. What you should do instead is introduce a counter to keep track of how many ticks to delay for. Then when you act you check if status is equal to 2, and if so, you decrement the counter, and only if it has reached zero do you then do the next action:
    public int status = 1;
    private int counter;
      
    public void act()   
    {  
        falle();  
    }     
      
    public boolean schalterAktiviert(){  
        Actor unter = getOneObjectAtOffset(0, getImage().getHeight(), Siggi.class);  
        return unter != null;      
    }  
      
    public void falle(){  
           if(schalterAktiviert() && status == 1){  
               getWorld().removeObjects(getWorld().getObjects(FalleZacken.class));   
               status = 2;
               counter = 100;
           }
           else if (status == 2) {
               if (counter == 0) {
                   if (! schalterAktiviert()) {
                       getWorld().addObject(new FalleZacken(), 400, 510);   
                       status = 1;  
                   }
               }
               else {
                   counter--;
               }
           }
    }  
Apart from that it looks almost right, but you have to invert the condition - use '! schalterAktiviert()' as in my code above - to check that the player has moved *away* from the lever.
You need to login to post a reply.