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

2014/12/2

Let an Object wait while the rest isnt waiting

Sleeyz Sleeyz

2014/12/2

#
I want to let my Object ( bullet ) wait everytime it moved. So when it moves x+1 it has to wait first before it goes again. I thought i can do this with Greenfoot.delay(1); but it doesnt work because it pauses the whole scenario, which i dont want to stop. Heres the code:
public void bulletMove()
    {
        
        System.out.println("Moved!");
        while(bulletCheck() == false )
        {
            
           
            int xPos = getX();
            int yPos = getY();
            int rotation = getRotation();
            
            switch(rotation)
            {
                case 0:                 
                this.setLocation(xPos + 1, yPos); 
                Greenfoot.delay(1);                                         
                break;
                
                case 90:
                this.setLocation(xPos, yPos + 1);
                Greenfoot.delay(1);                  
                break;
                
                case 180: 
                this.setLocation(xPos - 1, yPos);
                Greenfoot.delay(1);   
                break;
                
                case 270:
                this.setLocation(xPos, yPos - 1);
                Greenfoot.delay(1);  
                break;
            }
               
           
        }
      
    
        if(bulletCheck() == true )
        {
                getWorld().removeObject(this);
                System.out.println(this + " Got removed!");
        }
        
     
        
        
}
danpost danpost

2014/12/2

#
Unless you are required to use a switch statement in your code, this method can be reduced to the following:
public void bulletMove()
{
    System.out.println("Moved!");
    if (!bulletCheck())
    {
        move(1);
    }
    else
    {
        getWorld().removeObject(this);
        System.out.println(this + "Got removed!");
    }
}
To make it only process every other act cycle, you need to add a boolean instance field, change its value every act cycle and only process the code when the value is only either true or false. I change 'while' to 'if' because you do not want this code processing over and over again without other actors getting a chance to move at all. Either your actor will appear not to appear or your scenario will freeze because your code is executing an endless loop.
You need to login to post a reply.