Crab Scenario Animation


/ Published in: Java
Save to your folder(s)

I had a subtle mistake in my code that was causing the exception. The corrected source code is below:


Copy this code and paste it in your HTML
  1. import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)
  2.  
  3. /**
  4.  * This class defines a crab. Crabs live on the beach.
  5.  */
  6. public class Crab extends Animal
  7. {
  8. private final int MAX_TURN_DEGREES = 25;
  9. private final int ANIMATION_FRAMES = 2;
  10. private int animationCounter = 0;
  11. private GreenfootImage[] images;
  12.  
  13. public Crab()
  14. {
  15. images = new GreenfootImage[ANIMATION_FRAMES];
  16.  
  17. for( int i = 1; i <= ANIMATION_FRAMES; i++ )
  18. {
  19. images[i-1] = new GreenfootImage( "crab" + i + ".png" );
  20. }
  21. setImage( images[animationCounter] );
  22. animationCounter++;
  23. }
  24.  
  25. public void animate()
  26. {
  27. animationCounter = animationCounter % ANIMATION_FRAMES;
  28. setImage( images[animationCounter] );
  29. animationCounter++;
  30. }
  31.  
  32. public void turnAtEdge()
  33. {
  34. if( atWorldEdge() )
  35. {
  36. turn(17);
  37. }
  38. }
  39.  
  40. public void randomTurn()
  41. {
  42. if( Greenfoot.getRandomNumber(100) < 15 )
  43. {
  44. int directionToTurn = Greenfoot.getRandomNumber(3) - 1; // left, right, or no turn
  45. turn( directionToTurn * Greenfoot.getRandomNumber(MAX_TURN_DEGREES) );
  46. }
  47. }
  48.  
  49. public void lookForWorm()
  50. {
  51. if( canSee( Worm.class ) )
  52. {
  53. eat( Worm.class );
  54. Greenfoot.playSound("slurp.wav");
  55. }
  56. }
  57.  
  58. public void checkKeyPress()
  59. {
  60. if( Greenfoot.isKeyDown( "left" ) )
  61. {
  62. turn( -4 );
  63. }
  64. if( Greenfoot.isKeyDown( "right" ) )
  65. {
  66. turn( 4 );
  67. }
  68. }
  69.  
  70. public void act()
  71. {
  72. checkKeyPress();
  73. move();
  74. animate();
  75. lookForWorm();
  76. }
  77. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.