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

2021/2/18

Animation per act()

Philinö Philinö

2021/2/18

#
I'm trying to make a walking animation for automatically moving Camels, consisting in 2 sprites I made. The Object should switch out per act() round, but I have no clue how to do this.
RcCookie RcCookie

2021/2/18

#
You need to save which image is currently being shown. Since it’s only 2 images you can simply use a boolean for that:
// In your class, as a global variable
private boolean firstImage = true;
Then in your act method, you need to change the current image to the opposite one:
// Inside of act()
firstImage = !firstImage;
if(firstImage) setImage(„path/to/image1.png“);
else setImage(„path/to/image2.png“);
This however will load an image from a file every frame, which, like you might imagine, is not very efficient. The better way to do this is to load both images right away and store them:
// Globally
private GreenfootImage image1 = new GreenfootImage(„path/to/image1.png“);
private GreenfootImage image2 = new GreenfootImage(„path/to/image2.png“);
// In act()
firstImage = !firstImage;
if(firstImage) setImage(image1);
else setImage(image2);
// Or the last two lines shorter
setImage(firstImage ? image1 : image2);
Philinö Philinö

2021/2/19

#
RcCookie wrote...
You need to save which image is currently being shown. Since it’s only 2 images you can simply use a boolean for that:
// In your class, as a global variable
private boolean firstImage = true;
Then in your act method, you need to change the current image to the opposite one:
// Inside of act()
firstImage = !firstImage;
if(firstImage) setImage(„path/to/image1.png“);
else setImage(„path/to/image2.png“);
This however will load an image from a file every frame, which, like you might imagine, is not very efficient. The better way to do this is to load both images right away and store them:
// Globally
private GreenfootImage image1 = new GreenfootImage(„path/to/image1.png“);
private GreenfootImage image2 = new GreenfootImage(„path/to/image2.png“);
// In act()
firstImage = !firstImage;
if(firstImage) setImage(image1);
else setImage(image2);
// Or the last two lines shorter
setImage(firstImage ? image1 : image2);
Omg that worked so well, thank you!
You need to login to post a reply.