kilobolt creating game part iii

Upload: -

Post on 02-Jun-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 KiloBolt Creating Game Part III

    1/67

    GAME DEVELOPMENT TUTORIAL: DAY 3-1: Level Creation Part

    11/26/2012

    55 Comments

    Welcome to Unit 3. In the next several lessons, we will put our finishing touches on the game, adding levels,We are about half way finished with our first Java game. You've almost made it. Let's give it a final push.

    Today, we will begin a three part series on Level Creation. This series will entail reading a text file to create t

    objects that the character can interact with on the screen.

    We are implementing concepts that we have covered in the last 2 lessons of Unit 2. If you ever get confused,when you come back.

    Part 1: Common GroundWe will be picking up right where we left off at the end ofUnit 2, Day 8.If you have misplaced your files, or just want to start fresh, download the source code below:

    Download File

    Instructions on Importing Ecl

    Click Here(E

    Downloading Tiles & Background

    If you downloaded the source code above (unit3begin.zip), you can skip the downloading and just re

    Using your own code? Follow along.1. Download these two awesome tiles I created (please excuse my programmer art).Place 'em in the data folder.

    http://www.kilobolt.com/day-1-level-creation---part-1/game-development-tutorial-day-2-2-day-1-foundationshttp://www.kilobolt.com/day-1-level-creation---part-1/game-development-tutorial-day-2-2-day-1-foundations#commentshttp://www.kilobolt.com/day-1-level-creation---part-1/game-development-tutorial-day-2-2-day-1-foundations#commentshttp://www.kilobolt.com/day-8-animations.htmlhttp://www.kilobolt.com/day-8-animations.htmlhttp://www.kilobolt.com/day-8-animations.htmlhttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_begin.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_begin.ziphttp://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Ftasks%2Ftasks-importproject.htmhttp://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Ftasks%2Ftasks-importproject.htmhttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tileocean.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_begin.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tileocean.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_begin.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tileocean.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_begin.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tileocean.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_begin.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tileocean.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_begin.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tileocean.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_begin.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tileocean.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_begin.ziphttp://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Ftasks%2Ftasks-importproject.htmhttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_begin.ziphttp://www.kilobolt.com/day-8-animations.htmlhttp://www.kilobolt.com/day-1-level-creation---part-1/game-development-tutorial-day-2-2-day-1-foundations#commentshttp://www.kilobolt.com/day-1-level-creation---part-1/game-development-tutorial-day-2-2-day-1-foundations
  • 8/11/2019 KiloBolt Creating Game Part III

    2/67

    Download File Download File

    These two tiles are 40x40 pixels each. Since we are using a screen of size 800x480, we will be able to fit 20 at the top left).

    2. Also, we will be replacing my horrible background with this one:

    Download File

    Download and replace the original background.png!

    Part 2: Creating the Tile ClassWhat are we downloading all these images for?

    This is the desired effect:

    http://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tileocean.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tileocean.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/background.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/background.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/background.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/background.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/background.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tileocean.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.png
  • 8/11/2019 KiloBolt Creating Game Part III

    3/67

    The full Tile Class is to the right.

    Here's what I am doing (Ctrl+ tozoom):

    1.Create a new class called Tile.

    2. Add the following variables:Integers: tileX, tileY, speedX, type.

    Images: tileImage

    tileXrepresents the x coordinate

    (horizontal position) of the tile.

    tileYrepresents the y coordinate(vertical position) of the tile).speedXis equal to the speed of the tile.

    typeindicates whether the tile is an

    ocean tile or dirt tile.

    3. Create a Background object called

    bg, and point it to the bg1 object in

    Tile Classpackagekiloboltgame;

    importjava.awt.Image;

    publicclassTile {

    privateinttileX, tileY, speedX, tpublicImagetileImage;

    privateBackgroundbg =StartingClass.getBg1();

    publicTile(intx, inty, inttypeItileX =x *40;tileY =y *40;

    type =typeInt;

    http://www.google.com/search?hl=en&q=allinurl%3Aimage+java.sun.com&btnI=I%27m%20Feeling%20Luckyhttp://www.google.com/search?hl=en&q=allinurl%3Aimage+java.sun.com&btnI=I%27m%20Feeling%20Lucky
  • 8/11/2019 KiloBolt Creating Game Part III

    4/67

    StartingClass.This allows us to reference the bg1

    object within our tile class.

    4. Create a constructor.

    As I mentioned, each tile will have thevalue of 40 pixels. We will be creating

    Tiles using indexes, rather than pixels.

    This is why we multiple each index by40 to get the pixel location.

    For example, the tile in the upper left

    corner will have index (0, 0), so wemultiply 40 and still have (0, 0,) as

    tileX, tileY.

    However, for the adjacent tile (1, 0),the tileX and tileY will be (40, 0), just

    as we want it to be.

    5.Create an update() method.As with those of other classes, this

    update method will run on every loop(of the game loop).

    Type 1 is the ocean tile. We want it tomove slowly in the background;

    however, when the background isscrolling, we want the ocean to scroll

    faster to accommodate movement.

    Also, you will notice that this ocean

    scrolls slower than our character

    moves. This makes sense, because thecharacter is moving right in front of the

    camera, while the ocean is in the mid-

    ground. This isparallax scrolling at

    work, albeit simplified. And the same

    reason is why the ocean will scroll 5xfaster than the background layer (sky

    and clouds - we will be slowing itdown).

    6. The rest of the class is just gettersand setters (generated by right-clicking

    >> Source >> Generate Getters and

    if(type ==1){tileImage =StartingClass.ti

    }elseif(type ==2){

    tileImage =StartingClass.ti

    }

    }

    publicvoidupdate(){// TODO Auto-generated method s

    if(type ==1){if(bg.getSpeedX()==0){

    speedX =-1;}else{

    speedX =-2;}

    }else{speedX =bg.getSpeedX()*5;

    }

    tileX +=speedX;}

    publicintgetTileX(){returntileX;

    }

    publicvoidsetTileX(inttileX){this.tileX=tileX;

    }

    publicintgetTileY(){returntileY;

    }

    publicvoidsetTileY(inttileY){this.tileY=tileY;

    }

    publicImagegetTileImage(){returntileImage;

    }

    publicvoidsetTileImage(ImagetileI this.tileImage=tileImage;

    http://en.wikipedia.org/wiki/Parallax_scrollinghttp://en.wikipedia.org/wiki/Parallax_scrollinghttp://en.wikipedia.org/wiki/Parallax_scrollinghttp://www.google.com/search?hl=en&q=allinurl%3Aimage+java.sun.com&btnI=I%27m%20Feeling%20Luckyhttp://www.google.com/search?hl=en&q=allinurl%3Aimage+java.sun.com&btnI=I%27m%20Feeling%20Luckyhttp://www.google.com/search?hl=en&q=allinurl%3Aimage+java.sun.com&btnI=I%27m%20Feeling%20Luckyhttp://www.google.com/search?hl=en&q=allinurl%3Aimage+java.sun.com&btnI=I%27m%20Feeling%20Luckyhttp://en.wikipedia.org/wiki/Parallax_scrolling
  • 8/11/2019 KiloBolt Creating Game Part III

    5/67

    Setters. }

    }

    Part 3: Making a Few Changes1. Open up your Robot class. Now that we have multiple layers of backgrounds, we want the farthest one to s

    Locate the 4th if statement in the update()method inside the Robotclass.

    Make the following changes:

    if (speedX > 0 && centerX > 200){bg1.setSpeedX(-MOVESPEED/5);bg2.setSpeedX(-MOVESPEED/5);

    }

    Now the background will move at 1/5 the character's speed.

    2. Now open up your Enemy class and make the following changes to the update method (for the same reas

    // Behavioral Methodspublic void update() {

    centerX += speedX;speedX = bg.getSpeedX()*5;

    }

    Part 4: Adding the Tiles to StartingClassWe will be working with the StartingClass for Part 4.

    1. We begin at the class declaration. Add the following changes in bold.

    public class StartingClass extends Applet implements Runnable, KeyListener {

    private Robot robot;private Heliboy hb, hb2;private Image image, currentSprite, character, character2, character3,

    characterDown, characterJumped, background, heliboy, heliboy2,heliboy3, heliboy4, heliboy5;

    public static Image tiledirt, tileocean;

    private Graphics second;

    private URL base;private static Background bg1, bg2;private Animation anim, hanim;

    private ArrayList tilearray = new ArrayList();

    We have created two Image objects: tiledirtand tileocean, which will point to our PNG files. We have also c2. Then we scroll down to the //Image Setups section inside the init() method. Make the changes here

  • 8/11/2019 KiloBolt Creating Game Part III

    6/67

    // Image Setups

    character = getImage(base, "data/character.png");character2 = getImage(base, "data/character2.png");character3 = getImage(base, "data/character3.png");

    characterDown = getImage(base, "data/down.png");characterJumped = getImage(base, "data/jumped.png");

    heliboy = getImage(base, "data/heliboy.png");heliboy2 = getImage(base, "data/heliboy2.png");heliboy3 = getImage(base, "data/heliboy3.png");heliboy4 = getImage(base, "data/heliboy4.png");heliboy5 = getImage(base, "data/heliboy5.png");

    background = getImage(base, "data/background.png");

    tiledirt = getImage(base, "data/tiledirt.png");tileocean = getImage(base, "data/tileocean.png");

    3. Next, we must initialize the tilearray we created in step 1. Scroll down to the start() method, and ma

    @Overridepublic void start() {

    bg1 = new Background(0, 0);bg2 = new Background(2160, 0);

    // Initialize Tiles

    for (int i = 0; i < 200; i++) {

    for (int j = 0; j < 12; j++) {

    if (j == 11) {Tile t = new Tile(i, j, 2);tilearray.add(t);

    } if (j == 10) {Tile t = new Tile(i, j, 1);tilearray.add(t);

    }}

    }

    hb = new Heliboy(340, 360);hb2 = new Heliboy(700, 360);robot = new Robot();

    Thread thread = new Thread(this);thread.start();

    }We utilize a double for loop (as in Days 9, 10 of Unit 2), representing the x index of the tiles as i, and y index

  • 8/11/2019 KiloBolt Creating Game Part III

    7/67

    The numbers i < 200, j < 12 creates 2400 possible locations for tiles. Of those, we fill 400 (i = 200, j = 2).4. With the tilearray created, we must now update and paint the individual tiles inside the ArrayList.

    Create these two methods. Add them below the paint() method for organization:

    private void updateTiles() {

    for (int i = 0; i < tilearray.size(); i++) {Tile t = (Tile) tilearray.get(i);t.update();

    }

    }

    private void paintTiles(Graphics g) {for (int i = 0; i < tilearray.size(); i++) {

    Tile t = (Tile) tilearray.get(i);g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(), this);

    }}

    Both of these methods just utilize 1 index, looking at the size (the number of tiles) in tilearray. In the for loopand we therefore update our 2400 tiles and paint them.

    Look at the parameters inside the g.drawImagemethod, and make sense of them. We are drawing the imagcoordinate, and Y coordinate.5. All we now have to do is call these two methods.

    First. The updateTiles() method will be called inside the run() method. Place it above this statement like soupdateTiles();hb.update();

    Second. The paintTiles() method will be called inside the paint() method.We want the tiles to appear on toand enemies, so we place it below the two g.drawImage(background) methods like so:

    g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);paintTiles(g);

    Finished!Here's the final StartingClass code:package kiloboltgame;

    import java.applet.Applet;import java.awt.Color;import java.awt.Frame;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyEvent;

  • 8/11/2019 KiloBolt Creating Game Part III

    8/67

    import java.awt.event.KeyListener;import java.net.URL;import java.util.ArrayList;import kiloboltgame.framework.Animation;

    public class StartingClass extends Applet implements Runnable, KeyListener {

    private Robot robot;private Heliboy hb, hb2;private Image image, currentSprite, character, character2, character3,

    characterDown, characterJumped, background, heliboy, heliboy2,heliboy3, heliboy4, heliboy5;

    public static Image tiledirt, tileocean;

    private Graphics second;private URL base;private static Background bg1, bg2;private Animation anim, hanim;

    private ArrayList tilearray = new ArrayList();

    @Overridepublic void init() {

    setSize(800, 480);setBackground(Color.BLACK);setFocusable(true);addKeyListener(this);Frame frame = (Frame) this.getParent().getParent();frame.setTitle("Q-Bot Alpha");

    try { base = getDocumentBase();} catch (Exception e) {

    // TODO: handle exception}

    // Image Setupscharacter = getImage(base, "data/character.png");character2 = getImage(base, "data/character2.png");character3 = getImage(base, "data/character3.png");

    characterDown = getImage(base, "data/down.png");characterJumped = getImage(base, "data/jumped.png");

    heliboy = getImage(base, "data/heliboy.png");heliboy2 = getImage(base, "data/heliboy2.png");heliboy3 = getImage(base, "data/heliboy3.png");heliboy4 = getImage(base, "data/heliboy4.png");heliboy5 = getImage(base, "data/heliboy5.png");

    background = getImage(base, "data/background.png");

  • 8/11/2019 KiloBolt Creating Game Part III

    9/67

    tiledirt = getImage(base, "data/tiledirt.png");tileocean = getImage(base, "data/tileocean.png");

    anim = new Animation();anim.addFrame(character, 1250);anim.addFrame(character2, 50);

    anim.addFrame(character3, 50);anim.addFrame(character2, 50);

    hanim = new Animation();hanim.addFrame(heliboy, 100);hanim.addFrame(heliboy2, 100);hanim.addFrame(heliboy3, 100);hanim.addFrame(heliboy4, 100);hanim.addFrame(heliboy5, 100);hanim.addFrame(heliboy4, 100);hanim.addFrame(heliboy3, 100);hanim.addFrame(heliboy2, 100);

    currentSprite = anim.getImage();}

    @Overridepublic void start() {

    bg1 = new Background(0, 0);bg2 = new Background(2160, 0);

    // Initialize Tiles

    for (int i = 0; i < 200; i++) {for (int j = 0; j < 12; j++) {

    if (j == 11) {Tile t = new Tile(i, j, 2);tilearray.add(t);

    } if (j == 10) {Tile t = new Tile(i, j, 1);tilearray.add(t);

    }

    }}

    hb = new Heliboy(340, 360);hb2 = new Heliboy(700, 360);robot = new Robot();

    Thread thread = new Thread(this);thread.start();

    }

  • 8/11/2019 KiloBolt Creating Game Part III

    10/67

    @Overridepublic void stop() {

    // TODO Auto-generated method stub}

    @Override

    public void destroy() {// TODO Auto-generated method stub

    }

    @Overridepublic void run() {

    while (true) {robot.update();if (robot.isJumped()) {

    currentSprite = characterJumped;} else if (robot.isJumped() == false && robot.isDucked() == false) {

    currentSprite = anim.getImage();}

    ArrayList projectiles = robot.getProjectiles();for (int i = 0; i < projectiles.size(); i++) {

    Projectile p = (Projectile) projectiles.get(i);if (p.isVisible() == true) {

    p.update();} else {

    projectiles.remove(i);}

    }

    updateTiles();

    hb.update();hb2.update();bg1.update();bg2.update();animate();repaint();try {

    Thread.sleep(17);} catch (InterruptedException e) {

    e.printStackTrace();}

    }}

    public void animate() {anim.update(10);hanim.update(50);

    }

    @Overridepublic void update(Graphics g) {

    if (image == null) {

  • 8/11/2019 KiloBolt Creating Game Part III

    11/67

    image = createImage(this.getWidth(), this.getHeight());second = image.getGraphics();

    }

    second.setColor(getBackground());second.fillRect(0, 0, getWidth(), getHeight());

    second.setColor(getForeground());paint(second);

    g.drawImage(image, 0, 0, this);

    }

    @Overridepublic void paint(Graphics g) {

    g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);paintTiles(g);

    ArrayList projectiles = robot.getProjectiles();for (int i = 0; i < projectiles.size(); i++) {

    Projectile p = (Projectile) projectiles.get(i);g.setColor(Color.YELLOW);g.fillRect(p.getX(), p.getY(), 10, 5);

    }

    g.drawImage(currentSprite, robot.getCenterX() - 61,robot.getCenterY() - 63, this);

    g.drawImage(hanim.getImage(), hb.getCenterX() - 48,hb.getCenterY() - 48, this);

    g.drawImage(hanim.getImage(), hb2.getCenterX() - 48,

    hb2.getCenterY() - 48, this);}

    private void updateTiles() {

    for (int i = 0; i < tilearray.size(); i++) {Tile t = (Tile) tilearray.get(i);t.update();

    }

    }

    private void paintTiles(Graphics g) {

    for (int i = 0; i < tilearray.size(); i++) {Tile t = (Tile) tilearray.get(i);g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(), this);

    }}

    @Overridepublic void keyPressed(KeyEvent e) {

  • 8/11/2019 KiloBolt Creating Game Part III

    12/67

    switch (e.getKeyCode()) {case KeyEvent.VK_UP:

    System.out.println("Move up");break;

    case KeyEvent.VK_DOWN:

    currentSprite = characterDown;if (robot.isJumped() == false) {

    robot.setDucked(true);robot.setSpeedX(0);

    }break;

    case KeyEvent.VK_LEFT:robot.moveLeft();robot.setMovingLeft(true);break;

    case KeyEvent.VK_RIGHT:robot.moveRight();robot.setMovingRight(true);break;

    case KeyEvent.VK_SPACE:robot.jump();break;

    case KeyEvent.VK_CONTROL:if (robot.isDucked() == false && robot.isJumped() == false) {

    robot.shoot();}

    break;

    }

    }

    @Overridepublic void keyReleased(KeyEvent e) {

    switch (e.getKeyCode()) {case KeyEvent.VK_UP:

    System.out.println("Stop moving up");break;

    case KeyEvent.VK_DOWN:currentSprite = anim.getImage();robot.setDucked(false);break;

    case KeyEvent.VK_LEFT:robot.stopLeft();break;

  • 8/11/2019 KiloBolt Creating Game Part III

    13/67

  • 8/11/2019 KiloBolt Creating Game Part III

    14/67

    We will pick up from here in Day 2.

    That's It. Thanks for reading!

    http://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_day_1.ziphttp://facebook.com/kilobolthttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_day_1.ziphttp://facebook.com/kilobolthttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_day_1.ziphttp://facebook.com/kilobolthttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_day_1.ziphttp://facebook.com/kilobolt
  • 8/11/2019 KiloBolt Creating Game Part III

    15/67

    Download File

    GAME DEVELOPMENT TUTORIAL: DAY 3-2: LEVEL

    CREATION PART II11/30/2012

    58 Comments

    Continuing with the series, we have Part 2 of the Level Creation lessons. In this lesson, we will beadding a method that will read a .txtfile's information and draw a map to the screen accordingly.

    A typical map file may look like this:

    A map file

    In such a file, each space would represent a tile (or an empty tile), and we would be able to createcorresponding structures on the screen in this way.

    http://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_day_1.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_day_1.ziphttp://www.kilobolt.com/day-2-level-creation---part-2/game-development-tutorial-day-3-2-level-creation-part-iihttp://www.kilobolt.com/day-2-level-creation---part-2/game-development-tutorial-day-3-2-level-creation-part-iihttp://www.kilobolt.com/day-2-level-creation---part-2/game-development-tutorial-day-3-2-level-creation-part-ii#commentshttp://www.kilobolt.com/day-2-level-creation---part-2/game-development-tutorial-day-3-2-level-creation-part-ii#commentshttp://www.kilobolt.com/day-2-level-creation---part-2/game-development-tutorial-day-3-2-level-creation-part-ii#commentshttp://www.kilobolt.com/day-2-level-creation---part-2/game-development-tutorial-day-3-2-level-creation-part-iihttp://www.kilobolt.com/day-2-level-creation---part-2/game-development-tutorial-day-3-2-level-creation-part-iihttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit_3_day_1.zip
  • 8/11/2019 KiloBolt Creating Game Part III

    16/67

    Corresponding map on screenUsing this method, we will be able to create multiple levels for our character to traverse through.

    Let's begin.

    Making Changes to the StartingClassI. We will begin at the beginning by adding a few more types of tiles to the game.

    1. Find the line (yay syntax highlighting):publicstatic Image tiledirt,tileocean;

    And change it to this one:publicstaticImagetilegrassTop, tilegrassBot, tilegrassLeft,

    tilegrassRight, tiledirt;

    2. Find this segment in your init() method:

    tiledirt =getImage(base, "data/tiledirt.png");tileocean =getImage(base, "data/tileocean.png");

    Update like so:

    tiledirt =getImage(base, "data/tiledirt.png");tilegrassTop =getImage(base, "data/tilegrasstop.png");tilegrassBot =getImage(base, "data/tilegrassbot.png");tilegrassLeft =getImage(base, "data/tilegrassleft.png");tilegrassRight =getImage(base, "data/tilegrassright.png");

    II. You will want to download these (overwriting tiledirt.pngand deletingtileocean.png).They go inside your datafolder.

    Download File Download File Download File

    http://www.google.com/search?hl=en&q=allinurl%3Aimage+java.sun.com&btnI=I%27m%20Feeling%20Luckyhttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrasstop.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrasstop.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrassleft.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrassleft.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrassleft.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrasstop.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrassleft.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrasstop.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrassleft.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrasstop.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrassleft.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrasstop.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrassleft.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrasstop.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrassleft.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrasstop.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrassleft.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrasstop.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrassleft.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tilegrasstop.pnghttp://www.kilobolt.com/uploads/1/2/5/7/12571940/tiledirt.pnghttp://www.google.com/search?hl=en&q=allinurl%3Aimage+java.sun.com&btnI=I%27m%20Feeling%20Lucky
  • 8/11/2019 KiloBolt Creating Game Part III

    17/67

    Download File Download File

    While you're at it, download the map file also (place it also in the datafolder):

    III. Now that we got our assets ready, navigate to your start() method. In here, we have a double for loop that creates our Tile map. We will now be encapsulating thisinside a method. Find the following section:

    // Initialize Tiles

    for(inti =0;i

  • 8/11/2019 KiloBolt Creating Game Part III

    18/67

  • 8/11/2019 KiloBolt Creating Game Part III

    19/67

    }

    Let's now talk in detail about what this loadMap() method will do.

    LoadMap() MethodThe functions of this method are as follows:

    1. To create an ArrayList and fill it with the lines parsed from the .txt file.2. To utilize a double for loop to create tiles (we are basically rewriting the tile initializing for loops inthe init() method in this method).3. Assigning a type (recall in the last unit, we used integers to represent whether the tile was anocean tile or a grass tile) by reading the text file at the (x , y) index of the tile.

    The completed method looks like this:

    privatevoidloadMap(Stringfilename)throwsIOException{ArrayListlines =newArrayList();intwidth =0;intheight =0;

    BufferedReaderreader =newBufferedReader(newFileReader(filen while(true){

    Stringline =reader.readLine();// no more lines to readif(line ==null){

    reader.close();break;

    }

    if(!line.startsWith("!")){lines.add(line);width =Math.max(width, line.length());

    }}height =lines.size();

    for(intj =0;j

  • 8/11/2019 KiloBolt Creating Game Part III

    20/67

    }}

    }

    Now, we check what the character at the index i of the current line is (which has indexj). We thencreate a new Tile with the parameters x position, y position, and type. Since the characters we readfrom the text file are characters, not integers (there's a distinction between '1' and 1 much like there'sa distinction between "a" and a), we use a built-in method: Character.getNumericValue(ch)toconvert it to a number.

    The purpose of the if(i < line.length()){... statement is there to ensure that our i index neversearches for a character that does not exist. If this is not there, we can have all kinds of problemswith our map.txtso this is very important!

    Finishing TouchesNow all we have to do is handle the tile types inside the Tileclass. Make these changes to the if

    statements within the constructor, and we will be good to go!

    publicTile(intx, inty, inttypeInt){tileX =x *40;tileY =y *40;

    type =typeInt;

    if(type ==5){tileImage =StartingClass.tiledirt;

    }elseif(type ==8){tileImage =StartingClass.tilegrassTop;

    }elseif(type ==4){

    tileImage =StartingClass.tilegrassLeft;

    }elseif(type ==6){tileImage =StartingClass.tilegrassRight;

    }elseif(type ==2){tileImage =StartingClass.tilegrassBot;

    }

    }

    Finally, let me explain my reasoning for choosing the seemingly arbitrary typeIntvalues.

    If you look at a typical numpad:

  • 8/11/2019 KiloBolt Creating Game Part III

    21/67

    There are arrows below the numbers 8, 4, 6, and 2. I used these numbers to represent dirt tiles withgrass on the side that the arrows point towards. 5, of course, has no arrows and represents a dirt tilewith no grass on any side.

    Examine the map1.txt file to see how I applied this technique to create a simple level.

    At this time, you can run the code and it will work!

    In the next lesson, we will implement some basic collision detection to these tiles, and we will moveon from there! (Please don't send me emails saying "I can't jump on the platforms!" because wehaven't coded anything to make them platforms yet. They are as of now just images).

    Like Kilobolt Studios on Facebookand I will keep you posted.

    Download File

    GAME DEVELOPMENT TUTORIAL: DAY 3-3: LEVEL

    CREATION PART III12/07/2012

    18 Comments

    http://facebook.com/kilobolthttp://facebook.com/kilobolthttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit3day2.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit3day2.ziphttp://www.kilobolt.com/day-3-level-creation---part-3/game-development-tutorial-day-3-2-level-creation-part-iihttp://www.kilobolt.com/day-3-level-creation---part-3/game-development-tutorial-day-3-2-level-creation-part-iihttp://www.kilobolt.com/day-3-level-creation---part-3/game-development-tutorial-day-3-2-level-creation-part-ii#commentshttp://www.kilobolt.com/day-3-level-creation---part-3/game-development-tutorial-day-3-2-level-creation-part-ii#commentshttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit3day2.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit3day2.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit3day2.ziphttp://www.kilobolt.com/day-3-level-creation---part-3/game-development-tutorial-day-3-2-level-creation-part-ii#commentshttp://www.kilobolt.com/day-3-level-creation---part-3/game-development-tutorial-day-3-2-level-creation-part-iihttp://www.kilobolt.com/day-3-level-creation---part-3/game-development-tutorial-day-3-2-level-creation-part-iihttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit3day2.ziphttp://facebook.com/kilobolt
  • 8/11/2019 KiloBolt Creating Game Part III

    22/67

    Welcome to Day 3 of Unit 3. We will be continuing right where we left on in Day 2.

    In this lesson, we will clean up some of the code in the classes, and we will be conceptuallydiscussing collision detection, on which we will spend the next few lessons starting on Day 4.

    It will be a very short lesson, as the meat of the discussion will be thecollision detectionbasicsthat follow.

    I'm glad you are keeping up with the series, and I hope this lesson will be interesting!

    The first thing we will do will be some housekeeping. If you would rather skip all this, skip thecleaning steps and you will find the edited Robot, StartingClass, and Tiles classes below.

    Cleaning up our Robot ClassWe will need to make several changes to our code to ensure that we will be able to smoothlyimplement collision detection in the future.

    Most of these changes will deal with our Robot class. So let's open that up.

    When this class was created, we assumed that the ground would always be at a certain level. Wewill now be changing that.

    1. Remove the following lines of code highlighted in RED2. Make the changes as shown in GREEN

    http://www.kilobolt.com/collision-detection-basics.htmlhttp://www.kilobolt.com/collision-detection-basics.htmlhttp://www.kilobolt.com/collision-detection-basics.htmlhttp://www.kilobolt.com/collision-detection-basics.htmlhttp://www.kilobolt.com/collision-detection-basics.htmlhttp://www.kilobolt.com/collision-detection-basics.html
  • 8/11/2019 KiloBolt Creating Game Part III

    23/67

  • 8/11/2019 KiloBolt Creating Game Part III

    24/67

    Now this will break our game a little bit and our character will no longer be able to stand at "groundlevel" but we will be fixing that in the next lesson.

    Next, we want to do something about that shooting mechanism. Rather than let the player hold thebutton to shoot, we want him to repress the button each time.

    1. For that, we simply create a variable in the class declaration (add the following in Bold):

    private boolean movingLeft = false;private boolean movingRight = false;private boolean ducked = false;private boolean readyToFire = true;

    2. We want this new boolean to be accessible from other classes, so we right click >> source>> Generate Getters and Setters. Make sure that "readyToFire" is checked, and press OK.

    You can manually do this by adding:

    public boolean isReadyToFire() {

    return readyToFire;}

    public void setReadyToFire(boolean readyToFire) {this.readyToFire = readyToFire;

    }

    Wherever you feel appropriate.

    3. Now scroll down to the shoot()method, and surround the two statements around an if statementlike so:

    public void shoot() {if (readyToFire) {

    Projectile p = new Projectile(centerX + 50, centerY - 25);projectiles.add(p);

    }}

    This will ensure that only when the boolean "readyToFire" is true, the player will be able to shoot.

    4. Now, open up StartingClass. Navigate down to thekeyPressed()method. ForcaseKeyEvent.VK_CONTROL, you want to set it so that each time that robot.shoot()is called,

    readyToFire will be set to false.

    It will look like this:

    case KeyEvent.VK_CONTROL:if (robot.isDucked() == false && robot.isJumped() == false) {

    robot.shoot();robot.setReadyToFire(false);

    }

  • 8/11/2019 KiloBolt Creating Game Part III

    25/67

  • 8/11/2019 KiloBolt Creating Game Part III

    26/67

    The Resulting ClassesYou can use these to check for any mistakes.

    Robot Classpackagekiloboltgame;

    importjava.util.ArrayList;

    publicclassRobot{

    // Constants are HerefinalintJUMPSPEED =-15;finalintMOVESPEED =5;

    privateintcenterX =100;privateintcenterY =377;privatebooleanjumped =false;privatebooleanmovingLeft =false;privatebooleanmovingRight =false;privatebooleanducked =false;privatebooleanreadyToFire =true;

    privateintspeedX =0;privateintspeedY =0;

    privateBackground bg1 =StartingClass.getBg1();privateBackground bg2 =StartingClass.getBg2();

    privateArrayListprojectiles =newArrayList();

    publicvoidupdate(){// Moves Character or Scrolls Background accordingly.

    if(speedX 200){bg1.setSpeedX(-MOVESPEED /5);bg2.setSpeedX(-MOVESPEED /5);

    }

    // Updates Y PositioncenterY +=speedY;

    http://www.google.com/search?hl=en&q=allinurl%3Arobot+java.sun.com&btnI=I%27m%20Feeling%20Luckyhttp://www.google.com/search?hl=en&q=allinurl%3Arobot+java.sun.com&btnI=I%27m%20Feeling%20Lucky
  • 8/11/2019 KiloBolt Creating Game Part III

    27/67

    // Handles Jumpingif(jumped ==true){

    speedY +=1;

    }

    // Prevents going beyond X coordinate of 0if(centerX +speedX

  • 8/11/2019 KiloBolt Creating Game Part III

    28/67

    }

    publicvoidjump(){if(jumped ==false){

    speedY =JUMPSPEED;

    jumped =true;}

    }

    publicvoidshoot(){if(readyToFire){

    Projectile p =newProjectile(centerX +50, centerY -25);projectiles.add(p);

    }}

    publicintgetCenterX(){

    returncenterX;}

    publicintgetCenterY(){returncenterY;

    }

    publicbooleanisJumped(){returnjumped;

    }

    publicintgetSpeedX(){returnspeedX;

    }

    publicintgetSpeedY(){returnspeedY;

    }

    publicvoidsetCenterX(intcenterX){this.centerX=centerX;

    }

    publicvoidsetCenterY(intcenterY){this.centerY=centerY;

    }

    publicvoidsetJumped(booleanjumped){this.jumped=jumped;

    }

    publicvoidsetSpeedX(intspeedX){this.speedX=speedX;

    }

  • 8/11/2019 KiloBolt Creating Game Part III

    29/67

    publicvoidsetSpeedY(intspeedY){this.speedY=speedY;

    }

    publicbooleanisDucked(){returnducked;

    }

    publicvoidsetDucked(booleanducked){this.ducked=ducked;

    }

    publicbooleanisMovingRight(){returnmovingRight;

    }

    publicvoidsetMovingRight(booleanmovingRight){this.movingRight=movingRight;

    }

    publicbooleanisMovingLeft(){returnmovingLeft;

    }

    publicvoidsetMovingLeft(booleanmovingLeft){this.movingLeft=movingLeft;

    }

    publicArrayListgetProjectiles(){returnprojectiles;

    }

    }

    StartingClasspackage kiloboltgame;

    import java.applet.Applet;import java.awt.Color;import java.awt.Frame;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;

    import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.net.URL;import java.util.ArrayList;import kiloboltgame.framework.Animation;

    public class StartingClass extends Applet implements Runnable, KeyListener{

    http://www.google.com/search?hl=en&q=allinurl%3Aarraylist+java.sun.com&btnI=I%27m%20Feeling%20Luckyhttp://www.google.com/search?hl=en&q=allinurl%3Aarraylist+java.sun.com&btnI=I%27m%20Feeling%20Lucky
  • 8/11/2019 KiloBolt Creating Game Part III

    30/67

    private static Robot robot;private Heliboy hb, hb2;private Image image, currentSprite, character, character2, character3,

    characterDown, characterJumped, background, heliboy, heliboy2,heliboy3, heliboy4, heliboy5;

    public static Image tilegrassTop, tilegrassBot, tilegrassLeft,tilegrassRight, tiledirt;

    private Graphics second;private URL base;private static Background bg1, bg2;private Animation anim, hanim;

    private ArrayList tilearray = new ArrayList();

    @Overridepublic void init() {

    setSize(800, 480);setBackground(Color.BLACK);setFocusable(true);addKeyListener(this);Frame frame = (Frame) this.getParent().getParent();frame.setTitle("Q-Bot Alpha");try {

    base = getDocumentBase();} catch (Exception e) {

    // TODO: handle exception}

    // Image Setupscharacter = getImage(base, "data/character.png");character2 = getImage(base, "data/character2.png");character3 = getImage(base, "data/character3.png");

    characterDown = getImage(base, "data/down.png");characterJumped = getImage(base, "data/jumped.png");

    heliboy = getImage(base, "data/heliboy.png");heliboy2 = getImage(base, "data/heliboy2.png");heliboy3 = getImage(base, "data/heliboy3.png");heliboy4 = getImage(base, "data/heliboy4.png");heliboy5 = getImage(base, "data/heliboy5.png");

    background = getImage(base, "data/background.png");

    tiledirt = getImage(base, "data/tiledirt.png");tilegrassTop = getImage(base, "data/tilegrasstop.png");tilegrassBot = getImage(base, "data/tilegrassbot.png");tilegrassLeft = getImage(base, "data/tilegrassleft.png");tilegrassRight = getImage(base, "data/tilegrassright.png");

  • 8/11/2019 KiloBolt Creating Game Part III

    31/67

    anim = new Animation();anim.addFrame(character, 1250);anim.addFrame(character2, 50);anim.addFrame(character3, 50);anim.addFrame(character2, 50);

    hanim = new Animation();hanim.addFrame(heliboy, 100);hanim.addFrame(heliboy2, 100);hanim.addFrame(heliboy3, 100);hanim.addFrame(heliboy4, 100);hanim.addFrame(heliboy5, 100);hanim.addFrame(heliboy4, 100);hanim.addFrame(heliboy3, 100);hanim.addFrame(heliboy2, 100);

    currentSprite = anim.getImage();}

    @Overridepublic void start() {

    bg1 = new Background(0, 0);bg2 = new Background(2160, 0);robot = new Robot();// Initialize Tilestry {

    loadMap("data/map1.txt");} catch (IOException e) {

    // TODO Auto-generated catch blocke.printStackTrace();

    }

    hb = new Heliboy(340, 360);hb2 = new Heliboy(700, 360);

    Thread thread = new Thread(this);thread.start();

    }

    private void loadMap(String filename) throws IOException {ArrayList lines = new ArrayList();int width = 0;int height = 0;

    BufferedReader reader = new BufferedReader(newFileReader(filename));

    while (true) {String line = reader.readLine();// no more lines to readif (line == null) {

    reader.close();break;

  • 8/11/2019 KiloBolt Creating Game Part III

    32/67

    }

    if (!line.startsWith("!")) {lines.add(line);width = Math.max(width, line.length());

    }}height = lines.size();

    for (int j = 0; j < 12; j++) {String line = (String) lines.get(j);for (int i = 0; i < width; i++) {

    if (i < line.length()) {char ch = line.charAt(i);Tile t = new Tile(i, j,

    Character.getNumericValue(ch));tilearray.add(t);

    }

    }}

    }

    @Overridepublic void stop() {

    // TODO Auto-generated method stub}

    @Override

    public void destroy() {// TODO Auto-generated method stub

    }

    @Overridepublic void run() {

    while (true) {robot.update();if (robot.isJumped()) {

    currentSprite = characterJumped;} else if (robot.isJumped() == false && robot.isDucked() ==

    false) {currentSprite = anim.getImage();

    }

    ArrayList projectiles = robot.getProjectiles();for (int i = 0; i < projectiles.size(); i++) {

    Projectile p = (Projectile) projectiles.get(i);if (p.isVisible() == true) {

    p.update();} else {

    projectiles.remove(i);

  • 8/11/2019 KiloBolt Creating Game Part III

    33/67

    }}

    updateTiles();hb.update();hb2.update();

    bg1.update();bg2.update();animate();repaint();try {

    Thread.sleep(17);} catch (InterruptedException e) {

    e.printStackTrace();}

    }}

    public void animate() {

    anim.update(10);hanim.update(50);

    }

    @Overridepublic void update(Graphics g) {

    if (image == null) {image = createImage(this.getWidth(), this.getHeight());second = image.getGraphics();

    }

    second.setColor(getBackground());second.fillRect(0, 0, getWidth(), getHeight());

    second.setColor(getForeground());paint(second);

    g.drawImage(image, 0, 0, this);

    }

    @Overridepublic void paint(Graphics g) {

    g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);paintTiles(g);

    ArrayList projectiles = robot.getProjectiles();for (int i = 0; i < projectiles.size(); i++) {

    Projectile p = (Projectile) projectiles.get(i);g.setColor(Color.YELLOW);g.fillRect(p.getX(), p.getY(), 10, 5);

    }

    g.drawImage(currentSprite, robot.getCenterX() - 61,robot.getCenterY() - 63, this);

  • 8/11/2019 KiloBolt Creating Game Part III

    34/67

    g.drawImage(hanim.getImage(), hb.getCenterX() - 48,hb.getCenterY() - 48, this);

    g.drawImage(hanim.getImage(), hb2.getCenterX() - 48,hb2.getCenterY() - 48, this);

    }

    private void updateTiles() {

    for (int i = 0; i < tilearray.size(); i++) {Tile t = (Tile) tilearray.get(i);t.update();

    }

    }

    private void paintTiles(Graphics g) {for (int i = 0; i < tilearray.size(); i++) {

    Tile t = (Tile) tilearray.get(i);g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(),

    this);}

    }

    @Overridepublic void keyPressed(KeyEvent e) {

    switch (e.getKeyCode()) {case KeyEvent.VK_UP:

    System.out.println("Move up");break;

    case KeyEvent.VK_DOWN:

    currentSprite = characterDown;if (robot.isJumped() == false) {

    robot.setDucked(true);robot.setSpeedX(0);

    }break;

    case KeyEvent.VK_LEFT:robot.moveLeft();robot.setMovingLeft(true);break;

    case KeyEvent.VK_RIGHT:

    robot.moveRight();robot.setMovingRight(true);break;

    case KeyEvent.VK_SPACE:robot.jump();break;

    case KeyEvent.VK_CONTROL:

  • 8/11/2019 KiloBolt Creating Game Part III

    35/67

  • 8/11/2019 KiloBolt Creating Game Part III

    36/67

  • 8/11/2019 KiloBolt Creating Game Part III

    37/67

    publicvoidsetTileY(inttileY){

    this.tileY=tileY;}

    publicImagegetTileImage(){

    returntileImage;}

    publicvoidsetTileImage(ImagetileImage){this.tileImage=tileImage;

    }

    }

    Click to set custom HTMLNow let's talk about collision detection. As this information is more general, I will be discussing it in a

    new page (so it is easier to find).

    Click on the button below!

    Intro to Collision Detection: Collision Detection Basics

    12/07/2012

    18 Comments

    In this lesson, we will be discussing a few methods of collision detection and how one would goabout implementing them.

    What exactly does collision detection describe?To put simply, collision detection is a way of checking for object interaction.

    http://www.google.com/search?hl=en&q=allinurl%3Aimage+java.sun.com&btnI=I%27m%20Feeling%20Luckyhttp://www.google.com/search?hl=en&q=allinurl%3Aimage+java.sun.com&btnI=I%27m%20Feeling%20Luckyhttp://www.kilobolt.com/collision-detection-basics/intro-to-collision-detection-collision-detection-basicshttp://www.kilobolt.com/collision-detection-basics/intro-to-collision-detection-collision-detection-basics#commentshttp://www.kilobolt.com/collision-detection-basics/intro-to-collision-detection-collision-detection-basics#commentshttp://www.kilobolt.com/collision-detection-basics/intro-to-collision-detection-collision-detection-basics#commentshttp://www.kilobolt.com/collision-detection-basics/intro-to-collision-detection-collision-detection-basicshttp://www.google.com/search?hl=en&q=allinurl%3Aimage+java.sun.com&btnI=I%27m%20Feeling%20Luckyhttp://www.google.com/search?hl=en&q=allinurl%3Aimage+java.sun.com&btnI=I%27m%20Feeling%20Lucky
  • 8/11/2019 KiloBolt Creating Game Part III

    38/67

    In most real-time games (both old and new), collision detection is an integral element that holdseverything together. As such, a poor collision detection system can make the gaming experiencepainfully frustrating and, in worst scenarios, may even "break" your game.

    No one likes broken games.

    You should make every effort to implement as fluid and accurate a collision detection system asneeded by your game.

    How accurate must I be?Depending on your game, your needs will vary. If your game is extremely high speed, players mightnot notice if your collision detection is not fully accurate. On the other hand, if your game is an actionplatformer, players might notice if your character gets hit prematurely.

    You must spend time experimenting with your game to determine what system works best for you.

    What are some examples of Collision Detection?

    When Mega Man is jumping and sliding across platforms, the game is detecting a collision betweenthe character and the surface.

    When Mario leaps around to collect coins, the game checks to see if he has hit a coin and thenreacts by playing a sound, removing the coin from the screen, and adding to the score.

    If you are new to game development, the first thing you have to realize is that there are few built-inmethods of checking whether your objects are colliding, because pixels, which are just visualrepresentations, do not mean much to the computer.

    1. Bounding Rectangle/BoxCollisionsOne of the simplest ways to handle collision detection is the bounding rectangle method.

    If objects in your game can roughly be represented by a rectangle, this is probably the method youwould choose. In this method, you check for vertical and horizontal overlap and make changesaccordingly. Depending on the direction of the collision, your character may be lifted up or down orpushed left or right.

  • 8/11/2019 KiloBolt Creating Game Part III

    39/67

    Programatically, you might represent the above collision like this (this is very simplified as we do notcheck vertical position):

    = Assume the following =LetMegaMan.right be the x coordinate of the right side of the rectangle.

    Let Megaman.vX be MegaMan's velocity in the X direction.Let brick.left be the x coordinate of the left side of the rectangle.

    = Sample Code =if (MegaMan.right + MegaMan.vX > brick.left){

    System.out.println("Right side collision!") ;// Handle Collision

    }

    If we apply this concept to all four sides of the rectangle, then we would have a bounding rectanglecollision detection system.

    How exactly would we "handle collision?"In the example above, we might set MegaMan.vX equal to 0 so that Mega Man stops moving. Inaddition, we might change Mega Man's location so that the two rectangles are touching but nolonger intersecting. This way we do not have to repeatedly handle collision.

    How do you improve accuracy of this collision?The above system is not a very accurate one, as we will end up with results like this:

  • 8/11/2019 KiloBolt Creating Game Part III

    40/67

    With the above method, the game will register a collision even when certain parts of the sprite (thecharacter image) are far away from hitting something. This would lead to a poor user experience.

    Here are some solutions that you might try implementing:

    1. Reducing the Size of the RectangleRather than covering the tallest and widest parts of the character, you might try creating "a box ofbest fit." Doing this might improve collision significantly, and for most games, it might be perfectlysatisfactory.

    However if your game calls for a little more accuracy, you can always implement the next method.

    2. Use Multiple BoundsIf your game needs to check which part of the character was getting hit, then you might use thismethod.

    Rather than using one bounding box, you can use multiple ones as follows:

  • 8/11/2019 KiloBolt Creating Game Part III

    41/67

    This will ensure that collision is as close to the sprite as possible and will also give you more controlon each collision.

    The downside of this method, however, is that:1. Performance will suffer if you check too many collisions. 2. It takes a lot of time to implement.

    2. bOUNDING cIRCLE

    cOLLISIONSIf your game has handles a lot of balls, a bounding rectangle may not work best. In those situations,you will want to use Bounding Circles.

  • 8/11/2019 KiloBolt Creating Game Part III

    42/67

    Although you might think this will be complicated to implement, it is actually pretty simple due to thefact that a circle has a constant radius.

    In the above example (created using characters ofTUMBL)the radius of the two characters arerepresented by R1 and R2.

    http://www.kilobolt.com/tumbl-falldown.htmlhttp://www.kilobolt.com/tumbl-falldown.htmlhttp://www.kilobolt.com/tumbl-falldown.htmlhttp://www.kilobolt.com/tumbl-falldown.html
  • 8/11/2019 KiloBolt Creating Game Part III

    43/67

    Given the properties of circles, we can assume the following:

    1. If the distance between the centers of the two circles are greater than R1 + R2, they are notcolliding.2. If the distance between the centers of the two circles are LESSER than R1 + R2, then they mustbe colliding.

    How would we implement this system?Assuming that we know the (X, Y) coordinates of the two circles, this is rather simple to implement.We would use the distance formula (if you have a hard time remembering it, try to derive it as anapplication of the Pythagorean theorem): sqrt( (x1 - x2)^2 - (y1 - y2)^2) .

    We would then compare this value to R1 + R2, and then determine whether the two collided.

    What if we want to make them bounce off of each other?This would be slightly more tricky and would take a lot more time to implement, but it would not betoo difficult.

    By drawing a triangle using the distance formula, we can determine the angle of collision.

    Then we would proceed by using vectors and kinematic equations to determine the velocity anddirection that each character would be pushed. We won't be going over that in this lesson.

    Maybe in a future lesson!

  • 8/11/2019 KiloBolt Creating Game Part III

    44/67

    Of course, few games deal exclusively with circles, so there's always the third option!

    3. A Combination of BothIn TUMBL, the main character is circular and all the platforms are rectangular.

    By using techniques described above, you can create a collision detection system that incorporatesboth bounding rectangles and circles. Fun stuff!

    Where will we go from here?If you are following thegame development tutorials,we will be implementing a few of thesetechniques to our game.

    If you are not, be sure to check them out! They might be helpful.

    Thank you for reading, and please Likeus on Facebook if this guide helped you!

    GAME DEVELOPMENT TUTORIAL: DAY 3-4: COLLISIONDETECTION IWelcome to Day 4 of Unit 3!

    Now that we havediscussed collision detection in is basic form,we can start implementing thissystem to our game.Throughout the next few lessons, we will discuss a few types of collision detection; however, as thisis intended to be a beginner's course, we will not go into too much depth about sophisticatedsystems that you may want to implement into your own games.

    http://www.kilobolt.com/game-development-tutorial.htmlhttp://www.kilobolt.com/game-development-tutorial.htmlhttp://www.kilobolt.com/game-development-tutorial.htmlhttp://www.weebly.com/weebly/main.phphttp://www.weebly.com/weebly/main.phphttp://www.kilobolt.com/collision-detection-basics.htmlhttp://www.kilobolt.com/collision-detection-basics.htmlhttp://facebook.com/kilobolthttp://facebook.com/kilobolthttp://www.kilobolt.com/collision-detection-basics.htmlhttp://www.weebly.com/weebly/main.phphttp://www.weebly.com/weebly/main.phphttp://www.kilobolt.com/game-development-tutorial.html
  • 8/11/2019 KiloBolt Creating Game Part III

    45/67

    For that, I suggest you do further experimentation on your own!

    Let's begin today's lesson.

    Note: This is part 1 of a 3 part series on collision detection.

    Also note: This lesson does not have a comments section, because using a non-blog style lets mefully control the format and outline. I am experimenting with this to see if it works better.

    If you have questions or find errors, please email us at [email protected]

    bOUNDING rECTANGLESIn the aforementioned lesson, we discussed bounding shapes that will be used to check for collision.In the case of our robot, we will be using four bounding rectangles (as shown below).

    Today, however, we will only be handling vertical collision, and we will only deal with the yellow andorange rectangles.

    As Java includes a rectangle class, we can use some build-in methods that will allow us to savesome time. We will be checking the three rectangles above against the tiles (which will also berectangles) to check for collision.

    Collision detection basically involves checking whether there is an overlap of two objects andadjusting an object's (or objects') location to a non-overlapping spot before the game renders themistake.

    So how would we go about creating these rectangles (the yellow and orange for now)?

    Within the variables declarations section of the Robot class we will add the following in bold:

    private int speedX = 0;private int speedY = 0;public static Rectangle rect = new Rectangle(0, 0, 0, 0); public static Rectangle rect2 = new Rectangle(0, 0, 0, 0);

    This constructor creates Rectangle objects called rect and rect2 using (x, y, width, height).Make sure to import rectangles: Ctrl + Shift + O

    Then, we would update this within the updatemethod using the following statement.

    rect.setRect(centerX - 34, centerY - 63 , 68, 63);rect2.setRect(rect.getX(), rect.getY() + 63, 68, 64);

    We will add this to the very endof the method so that the rectangle's four corners will be as close tothe Robot image as possible.

  • 8/11/2019 KiloBolt Creating Game Part III

    46/67

    For debugging purposes, it is useful to render these rectangles.So let's do so by going to theStartingClass:1. Navigate to the paint method.2. Directly above the statement that paints the robot, add the following (in bold):

    g.drawRect((int)robot.rect.getX(), (int)robot.rect.getY(), (int)robot.rect.getWidth(),

    (int)robot.rect.getHeight());g.drawRect((int)robot.rect2.getX(), (int)robot.rect2.getY(), (int)robot.rect2.getWidth(),(int)robot.rect2.getHeight()); g.drawImage(currentSprite, robot.getCenterX() - 61, robot.getCenterY() - 63, this);

    Now you will have this result:

    Checking CollisionsNow that we have created these two bounds, we must check if they intersect with tiles.

    Open up the Tiles method.

    As with the Robot, each tile must be represented by a Rectangle also. This is easy to accomplish bycreating a Rectangle within the Tile constructor and updating its location in the tile's update method.

    1. Within the variable declarations, add the following:private Rectangle r;

  • 8/11/2019 KiloBolt Creating Game Part III

    47/67

    This r will represent the bounding rectangle for the given tile. When the tile is constructed, we willgive this a value by adding the following in bold:

    public Tile(int x, int y, int typeInt) {tileX = x * 40;tileY = y * 40;

    type = typeInt;

    r = new Rectangle();......

    2. Next, we have to create a method called checkVerticalCollision().Add this to the bottom of the class:

    public void checkVerticalCollision(Rectangle rtop, Rectangle rbot){if (rtop.intersects(r)){

    System.out.println("upper collision");}

    if (rbot.intersects(r)){System.out.println("lower collision");

    }}

    This method simply takes two rectangles as parameters and prints an appropriate response.

    3. We must now call this in the update method like so (shown in bold). We will also update therectangle r's values:

    public void update() {speedX = bg.getSpeedX() * 5;tileX += speedX;r.setBounds(tileX, tileY, 40, 40);

    if (type != 0){checkVerticalCollision(Robot.rect, Robot.rect2);

    }}

    4. Finally, we must make sure that graphically empty tiles (no platform is present) cannot collide with

    the robot. We do this by going back up to the constructor and adding the following in bold:

    if (type == 5) {tileImage = StartingClass.tiledirt;

    } else if (type == 8) {tileImage = StartingClass.tilegrassTop;

    } else if (type == 4) {tileImage = StartingClass.tilegrassLeft;

  • 8/11/2019 KiloBolt Creating Game Part III

    48/67

  • 8/11/2019 KiloBolt Creating Game Part III

    49/67

    Today, we will be checking for collision in the hands, and handling (correcting) both types ofcollisions.Before we implement the collision detection, let us first discuss how we will correct a collision.

    For our purposes, we will be checking two different things. The first testwill determine whether thecharacter is on the ground or in the air. The secondwill check which rectangle has hit something.

    If we are falling, we do not want our character to grab the platform with his hands. Therefore we willbe pretending that the arms do not exist while the character is in the air (it will seem slightly morerealistic because the arms will be lifted up). This, however, may cause problems for us if the armscollide after the character hits the ground, so we will have to deal with that appropriately.

    If we are on the ground (not ducking), we want to check the arms first and then the legs to determinewhich part of the body is colliding. That way, depending on the height of the platforms, our collisionswill adjust accordingly.

    If we are on the ground and we are ducking, then we want to check just the orange rectangle forcollisions.

    Now that we have planned our approach, let's begin.Keep these things in mind as you write code! Everything will make sense when youunderstand the strategy.

    Side Collision Detection1. Creating the RectanglesMuch like we did with vertical collision, we will be using intersecting rectangles for side collision.

    We begin in the Robot class.

    1. Create the two rectangles below (in bold):

    public static Rectangle rect = new Rectangle(0, 0, 0, 0);public static Rectangle rect2 = new Rectangle(0, 0, 0, 0);pub lic st atic Rectangle rect3 = n ew Rectang le(0, 0, 0, 0);

    pub l ic st atic Rectangle rect4 = n ew Rectang le(0, 0, 0, 0);

    We will use rect3 to refer to the left hand, and rect4 to refer to the right hand.

    2. Giving them these following values in the update method (in bold) will place them in the desiredlocation.Recall that the setRect method takes in parameters: (x, y, width, height).

    rect.setRect(centerX - 34, centerY - 63, 68, 63);rect2.setRect(rect.getX(), rect.getY() + 63, 68, 63);rect 3.setRect(rec t.getX() - 26, rect.getY()+32, 26, 20);

    rect 4.setRect(rec t.getX() + 68, rect.getY()+32, 26, 20);

    Doing this will properly update the two rectangles to represent their respective hands.

    3. If you choose, you can paint these rectangles in the paint method of the StartingClass; however,you would do this for debugging purposes, and since I have already tested the code that follows, youdo not need to paint them.

  • 8/11/2019 KiloBolt Creating Game Part III

    50/67

    When to Check CollisionsYou may have noticed from Day 4's lesson that I included a strange statement inthe Robotclass's update method:

    "if (true)..."

    This always defaults to true.The reason I included this statement was because I wanted to come back to it and make somechanges to it

    We only want to check collision for the tiles in the immediate vicinity to the robot. Therefore, we willlimit calling the collision checking methods to these 25 tiles (checkerboard):

    Now all that we have to do is replace if (true) with an if statement that will be true for only these 25squares.

    Here's how I would approach writing this statement.Notice that the tileX values for the 25 tiles described here will fall in the red region below.

    Identically, the tileY values for the 25 tiles fall in the yellow region.

  • 8/11/2019 KiloBolt Creating Game Part III

    51/67

    Therefore, we can create a rectangle that comprises this red width and yellow height and check if agiven tile intersects this rectangle. If it does, than the tile is one of the 25 in the checkerboard region,and we will have to check it for collision.

    Creating the Yellow-Red RectangleWe will now create this rectangle. Despite its name, we will not be coloring it.

    1. Create the yellowRed rectangle within the variable declarations section (make changes in bold):

    public static Rectangle rect = new Rectangle(0, 0, 0, 0);public static Rectangle rect2 = new Rectangle(0, 0, 0, 0);public static Rectangle rect3 = new Rectangle(0, 0, 0, 0);public static Rectangle rect4 = new Rectangle(0, 0, 0, 0);

    pub lic static Rectangle yel lowRed = new Rectang le(0, 0, 0, 0);

    2. Update it in the update() method with the following statement in bold::

    rect2.setRect(rect.getX(), rect.getY() + 63, 68, 63);rect3.setRect(rect.getX() - 26, rect.getY()+32, 26, 20);rect4.setRect(rect.getX() + 68, rect.getY()+32, 26, 20);yellowRed .setRect(c enterX - 110, centerY - 110, 180, 180);

    This will place the yellowRed rectangle at the appropriate location.

    Checking for CollisionsOpen up your Tileclass.

    Now that we have created the yellowRed rectangle, we can create an appropriate if statement forchecking collisions.

    1. Let's begin with the constructor Change the following in bold:

    public Tile(int x, int y, int typeInt) {tileX = x * 40;tileY = y * 40;

  • 8/11/2019 KiloBolt Creating Game Part III

    52/67

    type = typeInt;

    r = new Rectangle();

    if (type == 5) {

    tileImage = StartingClass.tiledirt;} else if (type == 8) {

    tileImage = StartingClass.tilegrassTop;} else if (type == 4) {

    tileImage = StartingClass.tilegrassLeft;

    } else if (type == 6) {tileImage = StartingClass.tilegrassRight;

    } else if (type == 2) {tileImage = StartingClass.tilegrassBot;

    } el se {typ e = 0;

    }

    }

    This ensures that all the "empty" tiles, which are simply tiles without images, will have type 0.

    2. Next we go down to the update() method. Make the following changes to the if statement:You will get errors. Please ignore them for now, as we will address them directly after.

    public void update() {speedX = bg.getSpeedX() * 5;tileX += speedX;r.setBounds(tileX, tileY, 40, 40);

    if (r.intersects(Robot.yellowRed) && type != 0) {checkVerticalCollision(Robot.rect, Robot.rect2);checkSideCollision(Robot.rect3, Robot.rect4, Robot.footleft,

    Robot.footright); }

    }

    Recall that the rectangle yellowRedis the "region of 25" tiles that will be checked for collision.

    Correcting the Errors

    The last changes probably introduced several errors to your code. We will be correcting those rightnow.

    Let's begin with the footleft, footrighterrors.

    1. Open up your Robot class and add the following statements to the variable declarations:

    pub lic st atic Rectangle fo otleft = n ew Rectang le(0,0,0,0);

    pub l ic static Rect angle foo trigh t = new Rectang le(0,0,0,0);

  • 8/11/2019 KiloBolt Creating Game Part III

    53/67

    2. Then add the following statements to the update() method.

    foo tleft.setRect(cen terX - 50, cen terY + 20, 50, 15);

    foo trigh t.setRect(centerX, centerY + 20, 50, 15);

    You can safely place them below all the other rectangles (if you need a reference, just scroll down topeek at the finished Robot class).

    These two rectangles are used for checking side collision when the tileis shorter than the arm height. They are simply small rectangles thatstick out a bit farther than the foot.

    Now moving on to the two methods.Add/Change the two methods in your Tile class to be as follows:

    public void checkVerticalCollision(Rectangle rtop, Rectangle rbot) {if (rtop.intersects(r)) {

    }

    if (rbot.intersects(r) && type == 8) {robot.setJumped(false);robot.setSpeedY(0);robot.setCenterY(tileY - 63);

    }}

    public void checkSideCollision(Rectangle rleft, Rectangle rright,

    Rectangle leftfoot, Rectangle rightfoot) {if (type != 5 && type != 2 && type != 0){

    if (rleft.intersects(r)) {robot.setCenterX(tileX + 102);

    robot.setSpeedX(0);

    }else if (leftfoot.intersects(r)) {robot.setCenterX(tileX + 85);robot.setSpeedX(0);

    }

    if (rright.intersects(r)) {robot.setCenterX(tileX - 62);

    robot.setSpeedX(0);}

    else if (rightfoot.intersects(r)) {robot.setCenterX(tileX - 45);robot.setSpeedX(0);

    }

  • 8/11/2019 KiloBolt Creating Game Part III

    54/67

    }}

    You will notice that these completed methods have various checks/tests. You should take the timeto go through each of them to make sense of each if statement.

    Final TouchesNow that we have completed the collision detection checking code, we must make a few changes.

    In the robot class:

    1. Locate the //Handles Jumping section of the update method.Make the following changes.

    // Handles Jumping

    speedY += 1;

    if (speedY > 3){jumped = true;

    }

    As we handle falling elsewhere, we can remove the first if statement.The if statement that I have created prevents small fluctuations in speedY from registering as jumps.

    2. You can now safely remove all the statements that paint our helper rectangles to the screen.

    The completed Robot, Tile, and StartingClass code is below:

    The Completed Robot Classpackage kiloboltgame;

    import java.awt.Rectangle;import java.util.ArrayList;

    public class Robot {

    // Constants are Herefinal int JUMPSPEED = -15;final int MOVESPEED = 5;

    private int centerX = 100;private int centerY = 377;private boolean jumped = false;

    private boolean movingLeft = false;private boolean movingRight = false;private boolean ducked = false;private boolean readyToFire = true;

    private int speedX = 0;private int speedY = 0;public static Rectangle rect = new Rectangle(0, 0, 0, 0);public static Rectangle rect2 = new Rectangle(0, 0, 0, 0);

  • 8/11/2019 KiloBolt Creating Game Part III

    55/67

    public static Rectangle rect3 = new Rectangle(0, 0, 0, 0);public static Rectangle rect4 = new Rectangle(0, 0, 0, 0);public static Rectangle yellowRed = new Rectangle(0, 0, 0, 0);

    public static Rectangle footleft = new Rectangle(0,0,0,0);public static Rectangle footright = new Rectangle(0,0,0,0);

    private Background bg1 = StartingClass.getBg1();private Background bg2 = StartingClass.getBg2();

    private ArrayList projectiles = newArrayList();

    public void update() {// Moves Character or Scrolls Background accordingly.

    if (speedX < 0) {centerX += speedX;

    }if (speedX == 0 || speedX < 0) {

    bg1.setSpeedX(0);bg2.setSpeedX(0);

    }if (centerX 0) {

    centerX += speedX;}if (speedX > 0 && centerX > 200) {

    bg1.setSpeedX(-MOVESPEED / 5);bg2.setSpeedX(-MOVESPEED / 5);

    }

    // Updates Y PositioncenterY += speedY;

    // Handles Jumping

    speedY += 1;

    if (speedY > 3){jumped = true;

    }

    // Prevents going beyond X coordinate of 0

    if (centerX + speedX

  • 8/11/2019 KiloBolt Creating Game Part III

    56/67

    footleft.setRect(centerX - 50, centerY + 20, 50, 15);footright.setRect(centerX, centerY + 20, 50, 15);

    }

    public void moveRight() {if (ducked == false) {

    speedX = MOVESPEED;}

    }

    public void moveLeft() {if (ducked == false) {

    speedX = -MOVESPEED;}

    }

    public void stopRight() {setMovingRight(false);stop();

    }

    public void stopLeft() {setMovingLeft(false);stop();

    }

    private void stop() {if (isMovingRight() == false && isMovingLeft() == false) {

    speedX = 0;

    }

    if (isMovingRight() == false && isMovingLeft() == true) {moveLeft();

    }

    if (isMovingRight() == true && isMovingLeft() == false) {moveRight();

    }

    }

    public void jump() {

    if (jumped == false) {speedY = JUMPSPEED;jumped = true;

    }

    }

    public void shoot() {if (readyToFire) {

  • 8/11/2019 KiloBolt Creating Game Part III

    57/67

  • 8/11/2019 KiloBolt Creating Game Part III

    58/67

    return movingRight;}

    public void setMovingRight(boolean movingRight) {this.movingRight = movingRight;

    }

    public boolean isMovingLeft() {return movingLeft;

    }

    public void setMovingLeft(boolean movingLeft) {this.movingLeft = movingLeft;

    }

    public ArrayList getProjectiles() {return projectiles;

    }

    public boolean isReadyToFire() {return readyToFire;

    }

    public void setReadyToFire(boolean readyToFire) {this.readyToFire = readyToFire;

    }

    }

    The Completed Tile Classpackage kiloboltgame;

    import java.awt.Image;import java.awt.Rectangle;

    public class Tile {

    private int tileX, tileY, speedX, type;public Image tileImage;

    private Robot robot = StartingClass.getRobot();private Background bg = StartingClass.getBg1();

    private Rectangle r;

    public Tile(int x, int y, int typeInt) {tileX = x * 40;tileY = y * 40;

    type = typeInt;

    r = new Rectangle();

  • 8/11/2019 KiloBolt Creating Game Part III

    59/67

    if (type == 5) {tileImage = StartingClass.tiledirt;

    } else if (type == 8) {tileImage = StartingClass.tilegrassTop;

    } else if (type == 4) {tileImage = StartingClass.tilegrassLeft;

    } else if (type == 6) {tileImage = StartingClass.tilegrassRight;

    } else if (type == 2) {tileImage = StartingClass.tilegrassBot;

    } else {type = 0;

    }

    }

    public void update() {

    speedX = bg.getSpeedX() * 5;tileX += speedX;r.setBounds(tileX, tileY, 40, 40);

    if (r.intersects(Robot.yellowRed) && type != 0) {checkVerticalCollision(Robot.rect, Robot.rect2);checkSideCollision(Robot.rect3, Robot.rect4,

    Robot.footleft, Robot.footright);}

    }

    public int getTileX() {

    return tileX;}

    public void setTileX(int tileX) {this.tileX = tileX;

    }

    public int getTileY() {return tileY;

    }

    public void setTileY(int tileY) {this.tileY = tileY;

    }

    public Image getTileImage() {return tileImage;

    }

    public void setTileImage(Image tileImage) {this.tileImage = tileImage;

    }

  • 8/11/2019 KiloBolt Creating Game Part III

    60/67

  • 8/11/2019 KiloBolt Creating Game Part III

    61/67

    import java.net.URL;import java.util.ArrayList;import kiloboltgame.framework.Animation;

    public class StartingClass extends Applet implements Runnable, KeyListener{

    private static Robot robot;private Heliboy hb, hb2;private Image image, currentSprite, character, character2, character3,

    characterDown, characterJumped, background, heliboy, heliboy2,heliboy3, heliboy4, heliboy5;

    public static Image tilegrassTop, tilegrassBot, tilegrassLeft,tilegrassRight, tiledirt;

    private Graphics second;private URL base;private static Background bg1, bg2;

    private Animation anim, hanim;

    private ArrayList tilearray = new ArrayList();

    @Overridepublic void init() {

    setSize(800, 480);setBackground(Color.BLACK);setFocusable(true);addKeyListener(this);Frame frame = (Frame) this.getParent().getParent();frame.setTitle("Q-Bot Alpha");

    try {base = getDocumentBase();

    } catch (Exception e) {// TODO: handle exception

    }

    // Image Setupscharacter = getImage(base, "data/character.png");character2 = getImage(base, "data/character2.png");character3 = getImage(base, "data/character3.png");

    characterDown = getImage(base, "data/down.png");characterJumped = getImage(base, "data/jumped.png");

    heliboy = getImage(base, "data/heliboy.png");heliboy2 = getImage(base, "data/heliboy2.png");heliboy3 = getImage(base, "data/heliboy3.png");heliboy4 = getImage(base, "data/heliboy4.png");heliboy5 = getImage(base, "data/heliboy5.png");

    background = getImage(base, "data/background.png");

  • 8/11/2019 KiloBolt Creating Game Part III

    62/67

    tiledirt = getImage(base, "data/tiledirt.png");tilegrassTop = getImage(base, "data/tilegrasstop.png");tilegrassBot = getImage(base, "data/tilegrassbot.png");tilegrassLeft = getImage(base, "data/tilegrassleft.png");tilegrassRight = getImage(base, "data/tilegrassright.png");

    anim = new Animation();anim.addFrame(character, 1250);anim.addFrame(character2, 50);anim.addFrame(character3, 50);anim.addFrame(character2, 50);

    hanim = new Animation();hanim.addFrame(heliboy, 100);hanim.addFrame(heliboy2, 100);hanim.addFrame(heliboy3, 100);hanim.addFrame(heliboy4, 100);hanim.addFrame(heliboy5, 100);hanim.addFrame(heliboy4, 100);

    hanim.addFrame(heliboy3, 100);hanim.addFrame(heliboy2, 100);

    currentSprite = anim.getImage();}

    @Overridepublic void start() {

    bg1 = new Background(0, 0);bg2 = new Background(2160, 0);robot = new Robot();// Initialize Tilestry {

    loadMap("data/map1.txt");} catch (IOException e) {

    // TODO Auto-generated catch blocke.printStackTrace();

    }

    hb = new Heliboy(340, 360);hb2 = new Heliboy(700, 360);

    Thread thread = new Thread(this);thread.start();

    }

    private void loadMap(String filename) throws IOException {ArrayList lines = new ArrayList();int width = 0;int height = 0;

    BufferedReader reader = new BufferedReader(newFileReader(filename));

    while (true) {String line = reader.readLine();

  • 8/11/2019 KiloBolt Creating Game Part III

    63/67

  • 8/11/2019 KiloBolt Creating Game Part III

    64/67

    if (p.isVisible() == true) {p.update();

    } else {projectiles.remove(i);

    }}

    updateTiles();hb.update();hb2.update();bg1.update();bg2.update();animate();repaint();try {

    Thread.sleep(17);} catch (InterruptedException e) {

    e.printStackTrace();}

    }}

    public void animate() {anim.update(10);hanim.update(50);

    }

    @Overridepublic void update(Graphics g) {

    if (image == null) {image = createImage(this.getWidth(), this.getHeight());second = image.getGraphics();

    }

    second.setColor(getBackground());second.fillRect(0, 0, getWidth(), getHeight());second.setColor(getForeground());paint(second);

    g.drawImage(image, 0, 0, this);

    }

    @Overridepublic void paint(Graphics g) {

    g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);paintTiles(g);

    ArrayList projectiles = robot.getProjectiles();for (int i = 0; i < projectiles.size(); i++) {

    Projectile p = (Projectile) projectiles.get(i);g.setColor(Color.YELLOW);g.fillRect(p.getX(), p.getY(), 10, 5);

  • 8/11/2019 KiloBolt Creating Game Part III

    65/67

  • 8/11/2019 KiloBolt Creating Game Part III

    66/67

    robot.jump();break;

    case KeyEvent.VK_CONTROL:if (robot.isDucked() == false && robot.isJumped() == false

    && robot.isReadyToFire()) {

    robot.shoot();robot.setReadyToFire(false);}break;

    }

    }

    @Overridepublic void keyReleased(KeyEvent e) {

    switch (e.getKeyCode()) {case KeyEvent.VK_UP:

    System.out.println("Stop moving up");break;

    case KeyEvent.VK_DOWN:currentSprite = anim.getImage();robot.setDucked(false);break;

    case KeyEvent.VK_LEFT:robot.stopLeft();break;

    case KeyEvent.VK_RIGHT:

    robot.stopRight();break;

    case KeyEvent.VK_SPACE:break;

    case KeyEvent.VK_CONTROL:robot.setReadyToFire(true);break;

    }

    }

    @Overridepublic void keyTyped(KeyEvent e) {

    // TODO Auto-generated method stub

    }

    public static Background getBg1() {return bg1;

  • 8/11/2019 KiloBolt Creating Game Part III

    67/67

    }

    public static Background getBg2() {return bg2;

    }

    public static Robot getRobot() {return robot;}

    }

    Download File

    Go to Unti 3: Day 4

    http://www.kilobolt.com/day-5-collision-detection-part-2.html

    IMA USTE

    http://www.kilobolt.com/uploads/1/2/5/7/12571940/unit3day5.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit3day5.ziphttp://www.kilobolt.com/day-4-collision-detection-part-1.htmlhttp://www.kilobolt.com/day-4-collision-detection-part-1.htmlhttp://www.kilobolt.com/day-5-collision-detection-part-2.htmlhttp://www.kilobolt.com/day-5-collision-detection-part-2.htmlhttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit3day5.ziphttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit3day5.ziphttp://www.kilobolt.com/day-5-collision-detection-part-2.htmlhttp://www.kilobolt.com/day-4-collision-detection-part-1.htmlhttp://www.kilobolt.com/uploads/1/2/5/7/12571940/unit3day5.zip