Actually, it does not create a new image every cycle, but only when the image changes. However, if you would rather not create any new images during the main running of the scenario, you could go with Vonmeth's second code-set.
If you wanted to give more structure to your code while not creating any new images during execution, you could use something like the following
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | // static and instance fieldsstatic final int LEFT=1, RIGHT=0;int facing=RIGHT;GreenfootImage[] sImg={ new GreenfootImage("sr.png"), new GreenfootImage("sr.png").mirrorHorizontally()) };GreenfootImage[][] wImg={ { new GreenfootImage("wr1.png"), new GreenfootImage("wr1.png").mirrorHorizontally()) }, { new GreenfootImage("wr2.png"), new GreenfootImage("wr2.png").mirrorHorizontally()) }, { new GreenfootImage("wr3.png"), new GreenfootImage("wr3.png").mirrorHorizontally()) }, { new GreenfootImage("wr4.png"), new GreenfootImage("wr4.png").mirrorHorizontally()) }, { new GreenfootImage("wr5.png"), new GreenfootImage("wr5.png").mirrorHoriztonally()) }, { new GreenfootImage("wr6.png"), new GreenfootImage("wr6.png").mirrorHorizontally()) } };// movement methodpublic void movement() // Hero's movement{ if(Greenfoot.isKeyDown("up")) // up { setLocation(getX(),getY()- mspeed/2); } if(Greenfoot.isKeyDown("down")) // down { setLocation(getX(),getY()+ mspeed/2); } if(Greenfoot.isKeyDown("left")) // left { setLocation(getX()- mspeed,getY()); facing = LEFT; } if(Greenfoot.isKeyDown("right")) // right { setLocation(getX()+ mspeed,getY()); facing = RIGHT; } if(!Greenfoot.isKeyDown("right") && !Greenfoot.isKeyDown("left") && !Greenfoot.isKeyDown("up") && !Greenfoot.isKeyDown("down")) { moveIndex = -1; } else { moveIndex++; } moveAnimation();}// moveAnimation methodpublic void moveAnimation(){ if (moveIndex >= 60) moveIndex=0; if (moveIndex % 10==0) { setImage(wImg[moveIndex/10][facing]); } if (moveIndex== -1) { setImage(sImg[facing]); }} |
