Detecting Collisions

Although you haven’t worked with gathering input from the user, you can instill a certain amount of responsiveness in the game by dealing with simple collisions with the walls of the tablet. A quick and simple implementation is shown in Listing 2-16.

Listing 2-16. Collision Code

if (sprite.getX() >= getWidth()){
        sprite.setMoveX(-2);
}
if (sprite.getX() <= 0){
        sprite.setMoveX(2);
}

Add this excerpt into the update method of the GameView.java file. It’s important to do this before the call to sprite.update() because you must handle any direction changes before you increment the position of the sprite.

You may notice that you reference a function that you haven’t yet created. To make this function work, the SpriteObject class needs two functions called setMoveX and setMoveY. The basic code for these is shown in Listing 2-17.

Listing 2-17. Collision Functions

public void setMoveX(int movex){
        x_move = movex;
}
public void setMoveY(int movey){
        y_move = movey;
}

Before you run this program, I manually changed the y_move to zero so that you can eliminate any up and down movement. When you play the program, the sprite should bounce back and forth between the right and left sides of the screen. There should be something strange about the movement, though: when the sprite gets to the far right onscreen, it disappears most of the way because you’re referencing your collisions on the location of the sprite, which is given by its center. You can eliminate any disappearance by taking into account the actual size and dimensions of the sprite.

If you wish to experiment with the necessary changes, go ahead and manipulate the if statement to reflect the sprite’s absolute left as well as its absolute right. Chapter 7 goes in depth in a discussion of collisions; you use the RECT element to precisely find intersections between different sprites and the walls or floor.

images Note Collision detection is a critical aspect of almost any game, and there are a variety of ways to go about it. When you later want to use bullets or other irregular shapes, you can employ a variety of polygons to find the intersection of sprites. A quick search on irregular collision detection yields a wealth of information to continue this topic.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.141.118