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

2015/10/4

Help with Little Crab Image Switching every 2nd or 3rd cycle

tomm1999 tomm1999

2015/10/4

#
Hello, I am using Little-Crab4 and trying to complete Exercise 4.27 in the book. Right now I have my crab image switch each cycle, but I need to change it to every 2 or 3 cycles. So I will have to add a counter and a if statement, but I am completely lost. Here is the question from the book: The crab image changes fairly quickly while the crab runs, which makes our little crab look a little hyperactive. Maybe it would look nicer if the crab image changed on every second or third act cycle. Try to implement this. To do this, you could add a counter that is incremented in the act method. Every time it reaches two (or Three), the image changes and the counter is reset to zero. Thank you for your help. Also, here is the code I currently have: /** * This class defines a crab. Crabs live on the beach. They like sand worms * (very yummy, especially the green ones). * * Version: 4 * * The crab is keyboard controlled and eats worms. In this version, we have added * a sound when the crab eats a worm. */ public class Crab extends Actor { private GreenfootImage image1; private GreenfootImage image2; public Crab() { //constructor only done once in life of crab image1 = new GreenfootImage("crab.png"); image2 = new GreenfootImage("crab2.png"); setImage(image1); } /** * Act - do whatever the crab wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { checkKeypress(); move(5); switchImage(); lookForWorm(); if ( isAtEdge() ) { turn(180); } } public void switchImage() { GreenfootImage tempImage; tempImage = getImage(); if ( tempImage == image1 ) setImage(image2); else setImage(image1); } /** * Check whether a control key on the keyboard has been pressed. * If it has, react accordingly. */ public void checkKeypress() { if (Greenfoot.isKeyDown("left")) { turn(-4); } if (Greenfoot.isKeyDown("right")) { turn(4); } } /** * Check whether we have stumbled upon a worm. * If we have, eat it. If not, do nothing. */ public void lookForWorm() { if ( isTouching(Worm.class) ) { removeTouching(Worm.class); Greenfoot.playSound("slurp.wav"); } } }
danpost danpost

2015/10/4

#
Well, you still have not included a counter; and you need to modify the 'switchImage' method so that the 'if' condition is based on the value of the counter instead of which image the actor currently is showing. You need to attempt something so that if you run into problems, we have something to work with. You will not learn anything if the solution is just given you.
tomm1999 tomm1999

2015/10/16

#
you are 100% right, I made a backup of what I had and started changing things until I got it. I searched the forum and that helped steer me in the right direction. Thanks for your reply
You need to login to post a reply.