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

2013/7/2

Using constructor local variable

davemib123 davemib123

2013/7/2

#
Hi, I am testing something out. I was trying to reduce the number of classes by combing some components together. I have a floating platform which can either go horizontally or vertically (2 separate classes)/ Like I said I was trying to combine them together, so I tried this:
public class FPlatform extends Ground
{
    
    public FPlatform(int selection)
    {
          this.speed = 2;
        setImage(FPlatform);       
        FPlatform.scale(170,30);
         if (selection == 1){
            moveHFPlatform();
        }
        else if (selection == 2){
            moveVFPlatform();
        }
    }
    
    /**
     * Act - do whatever the FPlatform wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        
         MovementCounter++;
         
    }    
}
If I try to place this class into the game, I get an error saying that actor is not in the world. Is what I am trying even possible?
davmac davmac

2013/7/2

#
Shouldn't the movement be in the act() method? (You need to save the 'selection' parameter into an instance variable so that the platform remembers which way it moves).
public class FPlatform extends Ground  
{  
    private int selection;
      
    public FPlatform(int selection)  
    {
        this.selection = selection;  // save the selection value
        setImage(FPlatform);         
        FPlatform.scale(170,30);  
    }

    public void act()
    {
        MovementCounter++; // not sure what this is for...
        if (selection == 1) {
            moveHFPlatform();
        }
        else if (selection == 2) {
            moveVFPlatform();
        }
    }
}
davemib123 davemib123

2013/7/2

#
Thanks Davmac, that works wonderfully. I tried almost what you had, I missed this line though:
this.selection = selection;
davemib123 davemib123

2013/7/2

#
Davmac that is such a neat technique. I've just applied it to a number of classes :)
You need to login to post a reply.