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

2014/1/1

how to use setimage

deathburrito16 deathburrito16

2014/1/1

#
the greenfoot reference pdf doesn't offer much help on this. Here is my current code.
    public void act() 
    {
        {
            if (Greenfoot.isKeyDown("w"))
            {
                move(1);
        }
        if (Greenfoot.isKeyDown("s"))
        {
            move(-1);
        }
        if (Greenfoot.isKeyDown("a"))
        {
            turn(-2);
            move(1);
        }
       if (Greenfoot.isKeyDown("d"))
        {
        turn(2);
        move(1);
    }}
    if (Greenfoot.isKeyDown("m"))
    {
        Bullet bullet = new Bullet();
        getWorld().addObject(bullet, getX() + 50, getY());
Greenfoot.setImage(playerfiring.png);
    }
shrucis1 shrucis1

2014/1/1

#
The Greenfoot setImage() Method takes a GreenfootImage as a parameter, not a filename. If you want to set the image to one with a filename of "playerfiring.png", you would do it like so:
public void act()   
{
    if (Greenfoot.isKeyDown("w"))  
    {
        move(1);  
    }  
    if (Greenfoot.isKeyDown("s"))  
    {  
        move(-1);  
    }  
    if (Greenfoot.isKeyDown("a"))  
    {  
        turn(-2);  
        move(1);  
    }  
    if (Greenfoot.isKeyDown("d"))  
    {  
        turn(2);  
        move(1);  
    }  
    GreenfootImage myImage;
    if (Greenfoot.isKeyDown("m"))  
    {  
        Bullet bullet = new Bullet();  
        getWorld().addObject(bullet, getX() + 50, getY());
        myImage = new GreenfootImage("playerfiring.png");
    }
    else {
        myImage = new GreenfootImage("playeridle.png");
        //Replace playeridle with whatever image you want to player to show when not firing.
    }
    setImage(myImage);
}
Also, I noticed you had some extra brackets that you didn't need, you might want to clean up your code a little bit. And keep in mind, the filename is case sensitive, and the image needs to be in the images folder.
deathburrito16 deathburrito16

2014/1/1

#
what do I need to replace myImage with?
danpost danpost

2014/1/1

#
Also, your new bullets will always appear 50 pixels to the right of the center of your player (regardless of the rotation of the player). That, and the bullets will all travel the same direction (probably to the right). To correct this, you might need something like the following in place of lines 24 and 25 above:
Bullet bullet = new Bullet();
getWorld().addObject(bullet, getX(), getY());
bullet.setRotation(getRotation());
bullet.move(50);
You need to login to post a reply.