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

2017/3/30

Help with shrinking an actor when another actor is touching it

Asiantree Asiantree

2017/3/30

#
public class Fries extends Actor
{
    private int height;
    private int width;
    
    public Fries (int height, int width)
    {
        this.height = height;
        this.width = width;
    }
    public void resizeImage()
    {
        GreenfootImage img = getImage();
        img.scale(height - 1, width - 1);
    }
    /**
     * Act - do whatever the Fries wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        List<Ant> touchingAnts = getIntersectingObjects(Ant.class);
        for (Ant a: touchingAnts)
        {
            resizeImage();
        }
    }    
}
I am trying to get the actor "Fries" to shrink in size by 1 pixel in height and width when an Ant is touching it. Any tips?
danpost danpost

2017/3/30

#
You probably have found that down-sizing the same image produces the original image with a cross-section missing (you end up with the four corners of the image (less than a quarter size of the original) butted up against each other. A transition something like this:
" A B C D E F G F E D C B A "          " A B C D E E D C B A "
" B C D E F G H G F E D C B "    >>    " B C D E F F E D C B "
" C D E F G H I H G F E D C "    >>    " B C D E F F E D C B "
" D E F G H I J I H G F E D "          " A B C D E E D C B A "
" C D E F G H I H G F E D C "
" B C D E F G H G F E D C B "
" A B C D E F G F E D C B A "
where the middle part and everything above, below and to either side is totally gone. To maintain a semblance of the original image, you need to scale a copy of the original each time to a smaller and smaller value. I see you already have 'height' and 'width' fields, which you are going to need; but, you also need a field for the original image. Add the following:
// instance field
GreenfootImage baseImage;

// in the constructor, add
baseImage = getImage();
Before scaling a copy of the base image, you should check to ensure that both the new height and width are positive values or you will produce an exception. So, the resizeImage method should be:
private void resizeImage()
{
    if (height > 1 && width > 1)
    {
        setImage(new GreenfootImage(baseImage));
        getImage().scale(--width, --height);
    }
}
Now, I noticed that you have the height and width values brought in by way of parameters in the constructor. Are your Fries objects going to have different initial sizes? or do you want the image to be initially resized (due to the original not being the size you want them to start at)? Answer both these questions will assist in verifying code accuracy.
You need to login to post a reply.