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

2015/6/16

Add Delay to Animation

greg.w902 greg.w902

2015/6/16

#
Hey, I would like to add a delay on the image switch of my player in my game, without changing the speed of the player moving. Below is the code for the image switching and the code for the actor that extends class which contains the changeDirection method. A delay that slows the image switch that makes it more realistic would be greatly appreciated. Thx for the help. public class AnimatedActor extends InteractiveMover { private GreenfootImage images; private int currentImage = 0; /** * Construct an animated actor. This assumes that you have provided image * file (in the 'images' folder) named 'basenameN.suffix', where N is * . * * @param basename The base name of the image files. * @param suffix The suffix of the image files (must include the "."). * @param noOfImages The number of images to be use din the animation. */ public AnimatedActor(String basename, String suffix, int noOfImages) { changeDirection(basename, suffix, noOfImages); } /** * Act - do whatever the AnimatedActor wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { currentImage = (currentImage + 1) % images.length; setImage(images); } public void changeDirection(String basename, String suffix, int noOfImages) { images = new GreenfootImage; for(int i=0; i < noOfImages; i++) { images = new GreenfootImage(basename + i + suffix); } setImage(images); } } //Separate Class public class Player1 extends AnimatedActor { public Player1() { super("Space_Man_right_",".png",2); } public void act() { super.act(); processKeys(); } public void moveLeft() { super.moveLeft(); changeDirection("Space_Man_left_",".png",2); } public void moveRight () { super.moveRight(); changeDirection("Space_Man_right_",".png",2); } }
danpost danpost

2015/6/16

#
As is, the range of values of 'currentImage' is equal to the number of images being used in the animation. If we let 'currentImage' go to twice the number of images and change the image every other time, we will effectively double the animation time, or cut the animation speed in half (it would take twice as long for one cycle of the animation to complete); or increasing the range limit to three times the number of images and changing the image every third time, it will slow down a bit more. Use:
1
2
3
4
5
currentImage = (currentImage+1)%(images.length*factor); // increment animation counter
if (currentImage%factor) == 0) // is time to change image
{
    setImage(images[currentImage/factor]); // set new image
}
The larger the value of 'factor', the slower the animation.
You need to login to post a reply.