Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 - Collision Detection: Asteroids Bruce Chittenden (modified by Jeff Goldstein)

Similar presentations


Presentation on theme: "Chapter 9 - Collision Detection: Asteroids Bruce Chittenden (modified by Jeff Goldstein)"— Presentation transcript:

1 Chapter 9 - Collision Detection: Asteroids Bruce Chittenden (modified by Jeff Goldstein)

2 9.1 Investigation: What is There? When experimenting with the current scenario, you will notice that some fundamental functionality is missing.  The rocket does not move. It cannot be turned, nor can it be moved forward.  Nothing happens when an asteroid collides with the rocket. It flies straight through it, instead of damaging the rocket.  As a result of this, you cannot lose. The game never ends, and a final score is never displayed.  The ScoreBoard, Explosion, and ProtonWave classes, which we can see in the class diagram, do not seem to feature in the scenario.

3 Exercise 9.1

4 Exercise 9.2 Controls for the Rocket Collision Logic Explosion Logic ScoreBoard Logic Implement ProtonWave

5 Exercise 9.3 Spacebar is used to fire a bullet

6 Exercise 9.4 Creates the Explosion Visual and makes and Explosion Sound

7 Exercise 9.5 The visual is Present, But It only shows the outer ring

8 9.2 Painting Stars The Asteroid Scenario does not use an image file for the background. A world that does not have a background image assigned will, by default, get an automatically created background image that is filled with plain white.

9 Exercise 9.6 The Background is Created by These Three Statements

10 Exercise 9.7 Code to Create the Background is Commented Out

11 Exercise 9.7

12 Exercise 9.8 Draw Rectangle Draw Oval Fill Oval

13 Exercise 9.8

14

15

16 Exercise 9.9

17 13 Defined Constant Fields

18 Exercise 9.10 /* * Method to create stars. The integer number is how many. */ private void createStars(int number) { // Need to add code here }

19 Exercise 9.11 /* * Method to create stars. The integer number is how many. */

20 Create 300 Stars Exercise 9.11

21 Exercise 9.13 Clean Compile

22 Exercise 9.14 /** * Add a given number of asteroids to our world. Asteroids are only added into * the left half of the world. */ private void addAsteroids(int count) { for(int i = 0; i < count; i++) { int x = Greenfoot.getRandomNumber(getWidth()/2); int y = Greenfoot.getRandomNumber(getHeight()/2); addObject(new Asteroid(), x, y); } The addAsteroids creates a count number of asteroids and adds them to the World

23 Exercise 9.15 for (int i = 0; i < count; i++) { } Initialization Loop-Condition Increment

24 Exercise 9.16 /* * Add a given number of asteroids to our world. Asteroids are only added into * the left half of the world. */ private void addAsteroids(int count) { int i = 0; while ( i < count) { int x = Greenfoot.getRandomNumber(getWidth()/2); int y = Greenfoot.getRandomNumber(getHeight()/2); addObject(new Asteroid(), x, y); i++; }

25 Exercise 9.17 /* * Add a given number of asteroids to our world. Asteroids are only added into * the left half of the world. */ private void addAsteroids(int count) { for ( int i = 0; i < count; i++) { int x = Greenfoot.getRandomNumber(getWidth()/2); int y = Greenfoot.getRandomNumber(getHeight()/2); addObject(new Asteroid(), x, y); }

26 Exercise 9.18 /* * Method to create stars. The integer number is how many. */ private void createStars(int number) { GreenfootImage background = getBackground(); for (int i = 0; i < number; i++) { int x = Greenfoot.getRandomNumber ( getWidth() ); int y = Greenfoot.getRandomNumber ( getHeight() ); background.setColor (new Color(255, 255, 255)); background.fillOval (x, y, 2, 2); } Generate a random number for x and y and place a star at that location

27 Exercise 9.18

28 Exercise 9.19 /* * Method to create stars. The integer number is how many. */ private void createStars(int number) { GreenfootImage background = getBackground(); for (int i = 0; i < number; i++) { int x = Greenfoot.getRandomNumber( getWidth() ); int y = Greenfoot.getRandomNumber( getHeight() ); int color = Greenfoot.getRandomNumber (256); background.setColor(new Color(color, color, color)); background.fillOval(x, y, 2, 2); } Generate a random number for color in the range 0 to 255

29 Exercise 9.19

30 9.3 Turning We want to make the rocket turn left or right using the left and right arrow keys.

31 Exercise 9.20 /* * Check whether there are any key pressed and react to them. */ private void checkKeys() { if (Greenfoot.isKeyDown("space")) { fire(); } The method checkKeys handles keyboard input

32 Exercise 9.21

33 Left (-) Degrees Right (+) Degrees if (Greenfoot.isKeyDown("left")) turn(-5);// alternate solution: setRotation(getRotation() - 5); if (Greenfoot.isKeyDown("right")) turn(5);// alternate solution: setRotation(getRotation() + 5);

34 Exercise 9.21 /* * Check whether there are any key pressed and react to them. */ private void checkKeys() { if (Greenfoot.isKeyDown ("space")) { fire(); } if (Greenfoot.isKeyDown ("left")) { turn(- 5); } If left arrow key is down rotate left 5 degrees

35 Exercise 9.21

36 Exercise 9.22 /* * Check whether there are any key pressed and react to them. */ private void checkKeys() { if (Greenfoot.isKeyDown("space")) { fire(); } if (Greenfoot.isKeyDown ("left")) { turn(- 5); } if (Greenfoot.isKeyDown ("right")) { turn(5); } If right arrow key is down rotate right 5 degrees

37 Exercise 9.22

38 9.4 Flying Forward Our Rocket class is a subclass of the SmoothMover class. This means that it holds a movement vector that determines its movement and that it has a move () method that makes it move according to this vector

39 Exercise 9.23 /* * Do what a rocket's gotta do. (Which is: mostly flying about, and turning, * accelerating and shooting when the right keys are pressed.) */ public void act() { move (); checkKeys(); reloadDelayCount++; } Add the move () method

40 Exercise 9.23 The rocket does not move because our move vector has not been initialized and contains zero

41 Exercise 9.24 /* * Initialize this rocket. */ public Rocket() { reloadDelayCount = 5; addToVelocity ( new Vector (13, 0.3)); //initially slow drifting } Add an initial movement to the rocket constructor.

42 Exercise 9.24 The rocket drifts slowly toward the right & slightly down

43 Exercise 9.25 /* * Check whether there are any key pressed and react to them. */ private void checkKeys() { if (Greenfoot.isKeyDown("space")) fire(); ignite (Greenfoot.isKeyDown ("up")); if (Greenfoot.isKeyDown("left")) turn(- 5); if (Greenfoot.isKeyDown("right")) turn(5); } Add a call to ignite

44 Exercise 9.26 /** * Go with thrust on */ private void ignite (boolean boosterOn) { } Define a stub method for ignite

45 Exercise 9.27 when “up” arrow key is pressed change image to show engine fire; add movement; when “up” arrow key is released change back to normal image; Pseudo code

46 Exercise 9.27 /* * Go with thrust on */ private void ignite (boolean boosterOn) { if (boosterOn) { setImage (rocketWithThrust); addToVelocity (new Vector (getRotation(), 0.3)); } else { setImage (rocket); } The ignite method complete

47 Exercise 9.27

48 9.5 Colliding with Asteroids If (we have collided with an asteroid) { remove the rocket from the world; place an explosion into the world; show final score (game over); } Pseudo code

49 Exercise 9.28 /* * Check for a collision with an Asteroid */ private void checkCollision() { } Define a stub method for checkCollision

50 Exercise 9.29 /* * Do what a rocket's gotta do. (Which is: mostly flying about, and turning, * accelerating and shooting when the right keys are pressed.) */ Public void act() { move (); checkKeys(); checkCollision(); reloadDelayCount++; } Make a call to checkCollision from the Rocket Act method

51 Intersecting Objects Bounding Box Visible Image List getIntersectingObjects (Class cls) Actor getOneIntersectingObject (Class cls)

52 Exercise 9.32 /* * Check for a collision with an Asteroid */ private void checkCollision() { Actor a = getOneIntersectingObject (Asteroid.class); if (a != null) { } Check for intersecting with an Asteroid (not null… we hit!)

53 Exercise 9.33 /* * Check for a collision with an Asteroid */ private void checkCollision() { Actor a = getOneIntersectingObject (Asteroid.class); if (a != null) { World world = getWorld(); world.removeObject (this); world.addObject (new Explosion(), getX(), getY()); } The problem with this code is that we removed the Object and then attempted to use its coordinates

54 Exercise 9.34

55

56 Exercise 9.34 (working) /* * Check for a collision with an Asteroid */ private void checkCollision() { Actor a = getOneIntersectingObject (Asteroid.class); if (a != null) { World world = (Space) getWorld(); world.addObject (new Explosion(), getX(), getY()); world.removeObject (this); } Add the code to display an explosion. Then remove Rocket from the World.

57 Exercise 9.35 This is a very advanced exercise. A more sophisticated way to show an explosion is introduced in the Greenfoot tutorial videos. Making Explosions, Part I Making Explosions, Part I (length: ~ 5 min) Making Explosions, Part II (length: ~ 10 min) Making Explosions, Part III (length: ~ 8.8 min) Making Explosions, Part II Making Explosions, Part III Making Explosions, Part IVMaking Explosions, Part IV (length: ~ 9.2 min) Making Explosions, Part V (length: ~ 6.3 min) Making Explosions, Part V Please view these explosion videos your author has prepared.

58 9.6 Game Over So, when should the game end? Now, the question is how to do it??? Suppose we end the game when we (our rocket) is struck by an asteroid.

59 Exercise 9.36 Right Click on ScoreBoard then click on new ScoreBoard and drag it into the World

60 Exercise 9.37 /* * Create a score board with dummy result for testing. */ public ScoreBoard() { this(100); } /* * Create a score board for the final result. */ public ScoreBoard(int score) { makeImage("Game Over", "Score: ", score); } The ScoreBoard class has two constructors, a Default Constructor and the one parameter Constructor

61 Exercise 9.38 public class ScoreBoard extends Actor { public static final float FONT_SIZE = 40.0f; public static final int WIDTH = 400; public static final int HEIGHT = 300; import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot) import java.awt.Color; import java.awt.Font; import java.util.Calendar; The information about Fonts is in java.awt.Font

62 Exercise 9.38 /* * Make a more interesting score board image. */ private void makeImage(String title, String prefix, int score) { GreenfootImage image = new GreenfootImage(WIDTH, HEIGHT); image.setColor(new Color(255,255,255, 68)); image.fillRect(0, 0, WIDTH, HEIGHT); image.setColor(new Color(0, 0, 0, 68)); image.fillRect(15, 15, WIDTH-15, HEIGHT-15); Font font = image.getFont(); font = font.deriveFont(ITALIC, FONT_SIZE); image.setFont(font); image.setColor(Color.RED); image.drawString(title, 60, 100); image.drawString(prefix + score, 60, 200); setImage(image); }

63 Example 9.38 (another example)

64 Exercise 9.39 gameOver Method is a stub

65 Exercise 9.40 /* * This method is called when the game is over to display the final score. * (Notice that the scoreboard neatly fits inside the space) */ public void gameOver() { addObject(new ScoreBoard(999), 300, 250); }

66 Exercise 9.42 /* * This method is called when the game is over to display the final score. */ public void gameOver() { addObject(new ScoreBoard(999), getWidth() / 2, getHeight() / 2); } To insure that the Score is placed in the of the World, center it at ½ width and ½ height

67 Exercise 9.43 (not working…yet) /* * Check for a collision with an Asteroid */ private void checkCollision() { Actor a = getOneIntersectingObject (Asteroid.class); if (a != null) { World world = (Space) getWorld(); world.addObject (new Explosion(), getX(), getY()); world.removeObject (this); world.gameOver(); } Add the code to display an explosion. Then remove Rocket from the World.

68 Exercise 9.43 The error comes from the fact that gameOver () is defined in class Space while getWorld returns a type of World. To solve this problem we tell the compiler explicitly that this world we are getting is actually of type Space. Error: but we need Space space = (space) getWorld(); // as a reference

69 Casting (will solve our problem) In computer science, type conversion, typecasting, and coercion refers to different ways of, implicitly or explicitly, changing an entity of one data type into another. This is done to take advantage of certain features of type hierarchies or type representations. One example would be small integers, which can be stored in a compact format and converted to a larger representation when used in arithmetic computations. In object-oriented programming, type conversion allows programs to treat objects of one type as one of their ancestor types to simplify interacting with them.computer sciencedata typeobject-oriented

70 Exercise 9.44 (working) /* * Check for a collision with an Asteroid */ private void checkCollision() { Actor a = getOneIntersectingObject (Asteroid.class); if (a != null) { Space space = (Space) getWorld(); space.addObject (new Explosion(), getX(), getY()); space.removeObject (this); space.gameOver(); } gameOver now has a reference to Space class where it is defined.

71 Exercise 9.44 (display)

72 Exercise 9.45 inconvertible types

73 9.7 Adding Fire Power: The Proton Wave The idea is this: Our proton wave, once released, radiates outward from our rocket ship, damaging or destroying every asteroid in its path. Since it works in all directions simultaneously, it is a much more powerful weapon than our bullets.

74 Exercise 9.46 Does not Move Does not Disappear Does not cause Damage

75 Exercise 9.47 public ProtonWave() { initializeImages(); } public static void initializeImages() { if(images == null) { GreenfootImage baseImage = new GreenfootImage("wave.png"); images = new GreenfootImage[NUMBER_IMAGES]; int i = 0; while (i < NUMBER_IMAGES) { int size = (i+1) * ( baseImage.getWidth() / NUMBER_IMAGES ); images[i] = new GreenfootImage(baseImage); images[i].scale(size, size); i++; } public void act() { } The Constructor and Two Methods ProtonWave () initializeImages () act ()

76 Exercise 9.48 /* * Create a new proton wave. */ public ProtonWave() { } /* * Create the images for expanding the wave. */ public static void initializeImages() { } /* * Act for the proton wave is: grow and check whether we hit anything. */ public void act() { }

77 Exercise 9.49 (explained) if we have not created the images, do so now get the base Image from the file wave.png create an array of NUMBER_IMAGES (30) images while there are still images to initialize calculate size of this image to be the width of image divided by the number of images multiplied by the index of this image set the next element in the array of images to the base image scaled to new size increment the number of images end of the while loop end of if images not created Pseudo code for initializeImages method

78 Figure 9.3: Growing the Wave GreenfootImage [ ] 0 1 2 3 4 29

79 Section 9.8: Code 9.3 /* * Create the images for expanding the wave. */ public static void initializeImages() { if (images == null) { GreenfootImage baseImage = new GreenfootImage("wave.png"); images = new GreenfootImage[NUMBER_IMAGES]; int i = 0; while (i < NUMBER_IMAGES) { int size = (i+1) * ( baseImage.getWidth() / NUMBER_IMAGES ); images[i] = new GreenfootImage(baseImage); images[i].scale(size, size); i++; }

80 Exercise 9.50 /* * Create the images for expanding the wave. */ public static void initializeImages() { if (images == null) { GreenfootImage baseImage = new GreenfootImage("wave.png"); images = new GreenfootImage[NUMBER_IMAGES]; for (int i = 0; i < NUMBER_IMAGES; i++) { int size = (i+1) * ( baseImage.getWidth() / NUMBER_IMAGES ); images[i] = new GreenfootImage(baseImage); images[i].scale(size, size); } for Loop

81 Exercise 9.51 /* * Create a new proton wave. */ public ProtonWave() { initializeImages(); setImage(images [0]); }

82 Exercise 9.51 (smallest image)

83 Exercise 9.52 /* * Current size of the wave. */ private int imageCount = 0;

84 Exercise 9.53 /* * Grow the wave. If we get to full size remove it. */ private void grow () { }

85 Exercise 9.54 /* * Act for the proton wave is: grow and check whether we hit anything. */ public void act() { grow(); } /* * Grow the wave. If we get to full size remove it. */ private void grow () { }

86 Exercise 9.55 if (our index has exceed the number of images) remove the wave from the world else set next image in the array & increment index end of if index is exceeded Pseudo code for grow method:

87 Exercise 9.55 /* * Grow the wave. If we get to full size remove it. */ private void grow () { if (imageCount >= NUMBER_IMAGES) getWorld().removeObject (this); else setImage(images[imageCount++]); }

88 Exercise 9.56 (testing) Right Click on ProtonWave Click on new ProtonWave() Drag into the World Click >Act to watch the wave grow

89 Exercise 9.57 /* * Create a new proton wave. */ public ProtonWave() { initializeImages(); setImage(images [0]); Greenfoot.playSound ("proton.wav"); } Add Sound

90 Exercise 9.58 (in the Rocket class) /* * Release a proton wave (if it is loaded). */ private void startProtonWave() { } Does Not Need Any Parameters and Does Not Return Anything

91 Exercise 9.59 /* * Release a proton wave (if it is loaded). */ private void startProtonWave() { ProtonWave wave = new ProtonWave(); getWorld().addObject (wave, getX(), getY()); }

92 Exercise 9.60 /* * Check whether there are any key pressed and react to them. */ private void checkKeys() { if (Greenfoot.isKeyDown("space")) fire(); if (Greenfoot.isKeyDown("z")) startProtonWave(); ignite (Greenfoot.isKeyDown ("up")); if (Greenfoot.isKeyDown("left")) turn(- 5); if (Greenfoot.isKeyDown("right")) turn(5); }

93 Exercise 9.60 (testing it)

94 Exercise 9.61 Proton Wave Can Be Released Too Fast by Holding Down the z Key

95 Exercise 9.61 private static final int gunReloadTime = 5; // The minimum delay between firing the gun. private static final int protonReloadTime = 200; // The minimum delay between proton wave bursts. private int reloadDelayCount; // How long ago we fired the gun the last time. private int reloadProtonDelayCount; // How long ago we fired proton wave the last time. private GreenfootImage rocket = new GreenfootImage("rocket.png"); private GreenfootImage rocketWithThrust = new GreenfootImage("rocketWithThrust.png"); A Delay Count of 200 Seems More Reasonable Than 500

96 Exercise 9.61 /* * Release a proton wave (if it is loaded). */ private void startProtonWave() { if (protonDelayCount >= protonReloadTime) { ProtonWave wave = new ProtonWave(); getWorld().addObject (wave, getX(), getY()); protonDelayCount = 0; } Improved version works if enough counts have elapsed

97 Exercise 9.61 (much better)

98 9.9 Interacting with Objects in Range List getObjectsInRange (int radius, Class cls)

99 Exercise 9.62 & 9.63 /* * act for the proton wave: checks asteroid collisions & grows the wave * (to avoid exceptions the order here is very important, too!) */ public void act() { checkCollision(); grow(); } /* * should a protonWave touch an asteroid, * explode all intersecting asteroids. */ private void checkCollision() { }

100 Exercise 9.64 /* * should a protonWave touch an asteroid, * explode all intersecting asteroids. */ private void checkCollision() { int range = getImage().getWidth() / 2; }

101 Exercise 9.65 import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot) import java.util.List; // important to add this import /* * Explode all intersecting asteroids. */ private void checkCollision() { int range = getImage().getWidth() / 2; List asteroids = getObjectsInRange (range, Asteroid.class); }

102 Exercise 9.66 /* * Hit this asteroid dealing the given amount of damage. */ public void hit(int damage) { stability = stability - damage; if(stability <= 0) breakUp (); } Before We Make Changes to the Method checkCollision (), Lets Look at the Hit Method Parameter is the Level of Damage

103 Exercise 9.67 /* The damage this wave will deal */ private static final int DAMAGE = 30;

104 Exercise 9.68 /* * Explode all intersecting asteroids. */ private void checkCollision() { int range = getImage().getWidth() / 2; List asteroids = getObjectsInRange (range, Asteroid.class); for (Asteroid a : asteroids) a.hit (DAMAGE); }

105 9.10 Further Development The following are some suggestions for future work, in the form of exercises. Many of them are independent of each other – they do not need to be done in this particular order. Pick those first that interest you most, and come up with some extension of your own.

106 Exercise 9.69 /* * Keep track of the score. */ public void countScore (int count) { scoreCounter.add(count); }

107 Exercise 9.69 private void breakUp() { Space space = (Space) getWorld(); // space is now a reference to Space class public methods Greenfoot.playSound("Explosion.wav"); if(size <= 16) // Removing an Asteroid is worth 25 points { getWorld().removeObject(this); space.countScore(25); } else // Splitting an Asteroid is worth 10 points { int r = getMovement().getDirection() + Greenfoot.getRandomNumber(45); double l = getMovement().getLength(); Vector speed1 = new Vector(r + 60, l * 1.2); Vector speed2 = new Vector(r - 60, l * 1.2); Asteroid a1 = new Asteroid(size/2, speed1); Asteroid a2 = new Asteroid(size/2, speed2); getWorld().addObject(a1, getX(), getY()); getWorld().addObject(a2, getX(), getY()); a1.move(); a2.move(); getWorld().removeObject(this); space.countScore(10); }

108 Exercise 9.69

109 9.11 Summary of Programming Techniques Understanding lists and loops is initially quite difficult, but very important in programming, so you should carefully review these aspects of your code if you are not yet comfortable in using them. The more practice you get, the easier it becomes. After using them for a while, you will be surprised that you found them so difficult at first.

110 9.11 Summary of Programming Techniques


Download ppt "Chapter 9 - Collision Detection: Asteroids Bruce Chittenden (modified by Jeff Goldstein)"

Similar presentations


Ads by Google