Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 - Collision Detection: Asteroids

Similar presentations


Presentation on theme: "Chapter 9 - Collision Detection: Asteroids"— 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 Spacebar is used to fire a bullet
Exercise 9.3 Spacebar is used to fire a bullet

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

7 The visual is Present, But It only shows the outer ring
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 The Background is Created by These Three Statements
Exercise 9.6 The Background is Created by These Three Statements

10 Code to Create the Background is Commented Out
Exercise 9.7 Code to Create the Background is Commented Out

11 Exercise 9.7

12 Exercise 9.8 Draw Oval Draw Rectangle Fill Oval

13 Exercise 9.8

14 Exercise 9.8

15 Exercise 9.8

16 Exercise 9.9

17 13 Defined Constant Fields
Exercise 9.9 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 Exercise 9.11 Create 300 Stars

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 for (int i = 0; i < count; i++) { }

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 Generate a random number for x and y and place a star at that location
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 Generate a random number for color in the range 0 to 255
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 The method checkKeys handles keyboard input
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 Exercise 9.21 if (Greenfoot.isKeyDown("left"))
turn(-5); // alternate solution: setRotation(getRotation() - 5); if (Greenfoot.isKeyDown("right")) turn(5); // alternate solution: setRotation(getRotation() + 5); Left (-) Degrees Right (+) Degrees

34 If left arrow key is down rotate left 5 degrees
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 If right arrow key is down rotate right 5 degrees
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 Add an initial movement to the rocket constructor.
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 The rocket drifts slowly toward the right & slightly down
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 Define a stub method for ignite
Exercise 9.26 Define a stub method for ignite /** * Go with thrust on */ private void ignite (boolean boosterOn) { }

45 Exercise 9.27 Pseudo code 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;

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

47 Exercise 9.27

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

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

50 Make a call to checkCollision from the Rocket Act method
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 boolean isTouching(Class cls) //  why not use it? Actor getOneIntersectingObject (Class cls) List getIntersectingObjects (Class cls) Bounding Box Visible Image

52 Check for intersecting with an Asteroid
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 The problem with this code is that we removed the Object and then attempted to use its coordinates /* * 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()); }

54 Exercise 9.34

55 Exercise 9.34

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 = 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 (length: ~ 5 min) Making Explosions, Part II (length: ~ 10 min) Making Explosions, Part III (length: ~ 8.8 min) Making Explosions, Part IV (length: ~ 9.2 min) Making Explosions, Part V (length: ~ 6.3 min) 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 The information about Fonts is in java.awt.Font
Exercise 9.38 The information about Fonts is in java.awt.Font import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot) import java.awt.Color; import java.awt.Font; import java.util.Calendar; 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;

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 gameOver Method is a stub
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 To insure that the Score is placed in the of the World, center it at
Exercise 9.42 To insure that the Score is placed in the of the World, center it at ½ width and ½ height /* * 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); }

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 = 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.

70 gameOver now has a reference to Space class where it is defined.
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 The Constructor and Two Methods ProtonWave ()
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) Pseudo code for initializeImages method
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

78 Figure 9.3: Growing the Wave
GreenfootImage [ ]

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 for Loop (extra credit +1)
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 (extra credit +1)

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 Pseudo code for grow method:
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

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

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 /* Add Sound * 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 A Delay Count of 200 Seems More Reasonable Than 500
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 Improved version works if enough counts have elapsed
Exercise 9.61 /* * Release a proton wave (if it is loaded). */ private void startProtonWave() { if (reloadProtonDelayCount >= protonReloadTime) ProtonWave wave = new ProtonWave(); getWorld().addObject (wave, getX(), getY()); reloadProtonDelayCount = 0; } // also, not in the book use reloadProtonDelayCount = 200 in the constructor // of the Rocket class so you can start firing the proton wave immediately. 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 range, 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<Asteroid> asteroids = getObjectsInRange (range, Asteroid.class); }

102 Exercise 9.66 Parameter is the Level of Damage /*
* 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

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<Asteroid> 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(); 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"

Similar presentations


Ads by Google