• Home
  • Tutorials
    • Game Development Tutorial>
      • Unit 1: Beginning Java>
        • Before you begin...
        • Day 1: Setting Up
        • Day 2: Java Basics
        • Day 3: More Basics
        • Day 4: Java Math
        • Day 5: More Math
        • Day 6: If... else...
        • Day 7: More Control Flow
        • Day 8: Looping
        • Day 9: More on Looping
        • Day 10: Inheritance, Interface
        • Day 11: Threads and Graphics
      • Unit 2: Creating a Game I>
        • Day 1: Foundations
        • Day 2: Basic Framework
        • Day 3: Taking User Input
        • Day 4: Enter the Robot
        • Day 5: Background and Sprites
        • Day 6: Adding Enemies
        • Day 7: Shooting Bullets
        • Day 8: Animations
        • Day 9: 2D-Arrays
        • Day 10: Painting the Tilemap
      • Unit 3: Creating a Game II>
        • Day 1: Level Creation - Part 1
        • Day 2: Level Creation - Part 2
        • Day 3: Level Creation - Part 3
        • Collision Detection Basics
        • Day 4: Collision Detection Part 1
        • Day 5: Collision Detection Part 2
        • Day 6: Collision Detection Part 3
        • Day 7: Health System & Death
        • Day 8: Basic AI & Final Touches
      • Unit 4: Android Game Development>
        • Day 1: Introduction to Android
        • Day 2: Setting up for Development
        • Day 3: Creating our First Android Application
        • Day 4: Parts of an Android Application
        • Day 5: The Android Game Framework: Part I
        • Day 6: The Android Game Framework: Part II
        • Create an Android Game From Scratch (or port your existing game)
        • Day 7: Creating an Android Game (From Start to Finish)
      • Reference Sheet
    • Zombie Bird Tutorial (Flappy Bird Remake)>
      • Unit 1: Building the Game>
        • Introduction
        • Day 1: Flappy Bird - An In-depth Analysis
        • Day 2: Setting up libGDX
        • Day 3: Understanding the libGDX Framework
        • Day 4: GameWorld and GameRenderer and the Orthographic Camera
        • Day 5: The Flight of the Dead - Adding the Bird
        • Day 6: Adding Graphics - Welcome to the Necropolis
        • Day 7: The Grass, the Bird and the Skull Pipe
        • Day 8: Collision Detection and Sound Effects
        • Day 9: Finishing Gameplay and Basic UI
        • Day 10: GameStates and High Score
        • Day 11: Supporting iOS/Android + SplashScreen, Menus and Tweening
        • Day 12: Completed UI & Source Code
    • Android Application Development Tutorial>
      • Unit 1: Writing Basic Android Apps>
        • Before you begin...
        • Day 1: Android 101
        • Day 2: Getting to Know the Android Project
        • Day 3: The Development Machine
        • Day 4: Building a Music App - Part 1: Building Blocks
        • Day 5: Building a Music App - Part 2: Intents
        • Day 6: Building a Music App - Part 3: Activity Lifecycles
  • New Forum
  • About Us
    • Contact Us
  • Our Games
    • TUMBL: FallDown
  • Facebook
  • Twitter

    GAME DEVELOPMENT TUTORIAL: DAY 3-4: COLLISION DETECTION I

Welcome to Day 4 of Unit 3!

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

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 me fully 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 support@kilobolt.com

bOUNDING rECTANGLES

In 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 and orange rectangles.
Picture
As Java includes a rectangle class, we can use some build-in methods that will allow us to save some time. We will be checking the three rectangles above against the tiles (which will also be rectangles) to check for collision.

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

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 update method 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 end of the method so that the rectangle's four corners will be as close to the Robot image as possible.

For debugging purposes, it is useful to render these rectangles. 
So let's do so by going to the StartingClass:
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:
Picture

Checking Collisions

Now 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 by creating 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;


This r will represent the bounding rectangle for the given tile. When the tile is constructed, we will give 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 the rectangle 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;

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

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


With that, your game should be able to check for vertical collisions. Since we will be adding a little bit more complexity in the next lessons, we will not be correcting the collision in this lesson. 

Now when you run the game, your console will output text to tell you whether you are colliding up or down (or both - since we have not made that impossible).

This was a short lesson, but we will be developing on these important concepts in the next lessons!

Repeating this one more time:

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 me fully control the format and outline. If you have questions or find errors, please email us at support@kilobolt.com

There is no source code for this lesson, because the next two lessons (which will be written immediately) will develop this code further. If you get errors, just move on and we will try to fix it all at the end!


Go to Collision Detection Basics
Go to Unit 3: Day 5
© 2014 Kilobolt, LLC. All rights reserved.