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

2013/5/4

Player Animation

GrimCreeper312 GrimCreeper312

2013/5/4

#
i'm am trying to animate my character so that when the player pressed space the image of the character with a sword comes up like a slide show. it also has to apply in the direction the character is facing i have a boolean variable facingRight. I'm trying to make it work with an array and a while loop but for some reason it doesn't work here is the array code.
String[] images =
    {"player_0","player_1","player_2","player_3","player_4","player_5","player_6","player_7","player_8","player_9",};
all images are .png player_0 is the default image with the player facing to the right. player_1 is the same as the first but is facing left. all the images for 2-5 are facing the left and 6-9 are facing to the right
A loop won't work because a loop will all happen in one frame (unless you add Greenfoot.delay() but in the case you want it, it won't turn out well). You need to instead have a counter and an if statement to reset that counter. I recommend something like this:
//instance variables
//your array
private int swordSwingCounter = 0;
private boolean swingingSword = false;

//in your act() method
if ((Greenfoot.isKeyDown("space") || swingingSword)
    swingSword();

//swingSword()
public void swingSword()
{
    swingingSword = true;  //Makes method run the frames after you press space
    setImage(new GreenfootImage(images[swordSwingingCounter]);
    swordSwingingCounter++;  //Increments counter, makes it that the next time this method is called, it will show the next frame according to your array
    if (swordSwingingCounter >= images.length)
    {
        swingingSword = false;  //Makes it that it won't go by itself
        swordSwingingCounter = 0;  //Reset counter
        setImage(/*Your default image file*/); //Resets image
    }
}
I hoped that helped!
You need to login to post a reply.