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

2017/3/7

Change Image

Fatum Fatum

2017/3/7

#
I'm now stuck in creating a game which is similar to Invaders. There's a class Wall which should change its Image when being touched be class Lazer; howecver, it does not work and I don't know why. That's my code.
public class Wall extends Defence
{
    static int num; //how many objects were hit
    public static int getWall(){
        return num;
    }
   
    public void act(){
        if (isTouching(Lazer.class)){
            for (int i=1; i<=32; i++){
            num=i;
         }
        } else {
            num=32;
        }
        if (num == 32){
            //GreenfootImage wallImage = new GreenfootImage("Wall1.png");
            setImage("Wall1.png");
        } else if (num < 32){
           // GreenfootImage wallImage = new GreenfootImage("Wall" + num + ".png");
           setImage("Wall" + num + ".png");
        }
    }
    }    
I would be incredibly grateful for any help with this question.
Nosson1459 Nosson1459

2017/3/7

#
In your act method just do:
if (isTouching(Lazer.class)) {
    setImage(/* name of file for new image */);
    // other things to do if laser touches wall
}
The for loop will make the variable 'num' be equal to 32 so the image will always be "Wall1.png".
Fatum wrote...
if (isTouching(Lazer.class)) {
    for (int i=1; i<=32; i++) {
        num=i;
    }
} else {
    num=32;
}
So basically if isTouching(Lazer.class) or not (else) num will be equal to 32. The for loop doesn't make sense because you're setting num = i but there is no other code being executed before or after that so the only difference in code will be the last thing 'i' is set to so that whole for loop will have the same result if you replaced it with:
num = 32;
to make num be less than 32 you can do
num = 31;

// or for whatever reason you want to use the for loop it will have to be
for (int i = 1; i < 32; i++) {
    num = i;
}
// at the end of this loop num will be == to 31
You need to login to post a reply.