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

2016/10/31

Trying to get actor to maintain the scale specified in code for constructor

JWK3986 JWK3986

2016/10/31

#
I'm trying to adjust the scale of an image used in a Fish Bowl scenario using a constructor, which works until I move the actor and it expands to the normal scale. How can I edit my code to keep the same size the whole time, which would ideally be a 1/2 scale?
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Goldfish here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Goldfish extends Actor
{
    private GreenfootImage image1 = new GreenfootImage ("goldfish.png");
    private GreenfootImage image2 = new GreenfootImage ("goldfish2.png");
    private int imageCounter;

    /**
     * Act - do whatever the Goldfish wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        fishSwim();
        checkKeys();

    }    

    public Goldfish()
    {
        GreenfootImage image = getImage();
        image.scale(image.getWidth()/2, image.getHeight()/2);
        setImage(image);

        
    }

    /**
     * Method to swap the goldfish images
     */

    public void goldfishImageSwap()
    {

        if (getImage().equals(image1)) {  
            setImage (image2);  
        }  
        else {  
            setImage (image1);
            
        }  

    }

    /**
     * Method to make the fish appear to swim
     */

    public void fishSwim()
    {
        if(Greenfoot.isKeyDown("right") == true)
        {
            move(2);
            imageCounter = (++imageCounter)%6; // change '2' higher to slow down animation
            if (imageCounter == 0) goldfishImageSwap();
        }
    }

    /**
     * Method for movement via keypresses
     */
    public void checkKeys()
    {

       
        if (Greenfoot.isKeyDown("up") == true)
        {
            setLocation(getX(), getY()+2);
        }
        else if (Greenfoot.isKeyDown("down") == true) 
        {
            setLocation(getX(), getY()-2);
        }

    }
}
danpost danpost

2016/10/31

#
Your constructor is only scaling the default image set to the actor. You need to scale both images that are referenced by the fields. You can remove the default image for the class and set one of the two reference images to the actor in the constructor:
public Goldfish()
{
    image1.scale(image1.getWidth()/2, image1.getHeight()/2);
    image2.scale(image2.getWidth()/2, image2.getHeight()/2);
    setImage(image1);
}
With this, you can replace line 42 with this:
if (getImage() == image1)
JWK3986 JWK3986

2016/11/1

#
Thank you, that works exactly the way I needed.
You need to login to post a reply.