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

2016/3/28

Trouble with if statements

grog2 grog2

2016/3/28

#
I'm making an object that is meant to change image when HitDetect() returns true, and also set transparency to 0 when the object is at the edge, but I can't get it to do both.
if (getY() <= 1 || getX() <= 1 || getY() >= 599 || getX() >= 799) 
        {
            getImage().setTransparency(0);
        }
        else
        {
            getImage().setTransparency(255);
        }
        if (hitDetect() == true)
        {
            setImage(new GreenfootImage("TowerCopy.png"));
        }
        else
        {
            setImage(new GreenfootImage("Tower.png"));
        }
When I run this, the second if works fine but the first doesn't and when I remove the second one, the first works fine. Help?
Super_Hippo Super_Hippo

2016/3/28

#
Move lines 9-16 to the beginning. As it is now, you change the transparency of the current image and change the image after that which has the default transparency again.
danpost danpost

2016/3/28

#
Of note: it is more CPU-intensive to create and set a new image to the actor every act cycle. Better would be to hold the images in class fields and only change the image when the value returned from 'hitDetect' changes:
// class fields
private static final GreenfootImage HIT_IMAGE = new GreenfootImage ("TowerCopy.png");
private static final GreenfootImage IMAGE = new GreenfootImage("Tower.png");

// instance fields
private boolean hitDetected; // to track return of 'hitDetect' method (initial value of 'false')

// in constructor of class
setImage(IMAGE); // initial image setting

// execution code
if (hitDetect() != hitDetected) // change in returned value
{
    hitDetected = !hitDetected; // update tracking field
    setImage(hitDetected ? HIT_IMAGE : IMAGE); // update image depending on new value of 'hitDetected'
}
grog2 grog2

2016/3/28

#
Thanks, this is really helpful!
You need to login to post a reply.