• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
mgowtam

Ping pong game collision detection error

3 posts in this topic


Hello all, I'm a beginner, just trying to learn the elements of game development. I am creating a ping pong game clone, with allegro library. Following are the classes in my program:
1.Paddle
2.AiPaddle
3.Ball
 
1.Paddle.cpp code:
#include "paddle.h"
#include <iostream>

bool Paddle::init()
{
	p = new Position();
	p->x = 0.0;
	p->y = SCREEN_HEIGHT/2.0;

	v = new Velocity();
	v->x = 4.0;
	v->y = 4.0;

	image = al_load_bitmap("paddle1.png");

	if (!image) {
		std::cout<<"in padd init!"<<std::endl;
		return false;
	}
	return true;
}

ALLEGRO_BITMAP* Paddle::getBitmap()
{
	return image;
}

float Paddle::getHeight()
{
	return al_get_bitmap_height(image);
}

float Paddle::getWidth()
{
	return al_get_bitmap_width(image);
}

Position* Paddle::getPosition()
{
	return p;
}

Velocity*  Paddle::getVelocity()
{
	return v;
}

void Paddle::move(ALLEGRO_KEYBOARD_STATE* keyState)
{
	if ( al_key_down(keyState, ALLEGRO_KEY_DOWN) ) {
		if(p->y+getHeight() < SCREEN_HEIGHT ) {
			p->y += v->y;
		}
	} else if ( al_key_down(keyState, ALLEGRO_KEY_UP) ) {
		if ( (p->y - v->y) >= 0 ) {
			p->y -= v->y;
		}
	}
}

void Paddle::draw()
{
	al_draw_bitmap(image, p->x, p->y,0);
} 

2. AiPaddle.cpp code:

#include "ai_paddle.h"
#include <iostream>

bool AiPaddle::init()
{
	p = new Position();
	p->y = SCREEN_HEIGHT/2.0;

	v = new Velocity();
	v->x = 4.0;
	v->y = 4.0;

	image = al_load_bitmap("paddle1.png");
	p->x = SCREEN_WIDTH - al_get_bitmap_width(image);

	if (!image) {
		std::cout<<"in padd init!"<<std::endl;
		return false;
	}
	return true;
}

ALLEGRO_BITMAP* AiPaddle::getBitmap()
{
	return image;
}

float AiPaddle::getHeight()
{
	return al_get_bitmap_height(image);
}

float AiPaddle::getWidth()
{
	return al_get_bitmap_width(image);
}

Position* AiPaddle::getPosition()
{
	return p;
}

Velocity*  AiPaddle::getVelocity()
{
	return v;
}

void AiPaddle::move(ALLEGRO_KEYBOARD_STATE* keyState)
{
	if ( al_key_down(keyState, ALLEGRO_KEY_DOWN) ) {
		if(p->y+getHeight() < SCREEN_HEIGHT ) {
			p->y += v->y;
		}
	} else if ( al_key_down(keyState, ALLEGRO_KEY_UP) ) {
		if ( (p->y - v->y) >= 0 ) {
			p->y -= v->y;
		}
	}
}

void AiPaddle::draw()
{
	al_draw_bitmap(image, p->x, p->y,0);
}

void AiPaddle::update(Velocity* ball_velocity, Position* ball_position)
{
	if ( ball_velocity->x > 0 ) {
		if ( ball_velocity->y > 0 && p->y + getHeight() < ball_position->y ) {
			if(p->y+getHeight() < SCREEN_HEIGHT ) {
				p->y += v->y;
			}
		} else {
			if ( (p->y - v->y) >= 0 && p->y > ball_position->y ) {
				p->y -= v->y;
			}
		}
	}		
}

 

3.Ball.cpp code:

#include "ball.h"

bool Ball::init()
{
	p = new Position();
	p->x = 0.0;
	p->y = 200.0;

	v = new Velocity();
	v->x = 3.0;
	v->y = 2.0;

	image = al_load_bitmap("ball1.png");
	
	if(!image) {
		return false;
	}
	return true;
}

bool Ball::collisionWithWall()
{
	bool collision_flag = false;

	if ( p->y <= 0 || p->y + getHeight() >= SCREEN_HEIGHT ) {
		collision_flag = true;
	}

	return collision_flag;
}

bool Ball::collisionWithPaddles(Paddle* pd, AiPaddle* aipd)
{
	bool collision_flag = false;

	if( p->y >= pd->getPosition()->y && p->y <= (pd->getPosition()->y+pd->getHeight()) ) {
		if ( p->x <= (pd->getPosition()->x+pd->getWidth()) ) {
			collision_flag = true;
		}
	} else if ( p->y >= aipd->getPosition()->y && p->y <= (aipd->getPosition()->y+aipd->getHeight()) ) {
		if ( p->x+getWidth() >= (aipd->getPosition()->x) ) {
			collision_flag = true;
		}
	}

	return collision_flag;
}

void Ball::update(Paddle* pd, AiPaddle* aipd)
{
	if ( collisionWithPaddles(pd, aipd) ) {
		v->x = -v->x;
	} else if ( p->y <= 0 || p->y + getHeight() >= SCREEN_HEIGHT ) {
		v->y = -v->y;
	}
	p->x += v->x;
	p->y += v->y;
}

Position* Ball::getPosition()
{
	return p;
}

Velocity* Ball::getVelocity()
{
	return v;
}

void Ball::draw()
{
	al_draw_bitmap(image, p->x, p->y, 0);
}

float Ball::getHeight()
{
	return al_get_bitmap_height(image);
}

float Ball::getWidth()
{
	return al_get_bitmap_width(image);
}

 

4. Main function:

#include <iostream>
#include <stdio.h>
#include <allegro5/allegro.h>
#include "allegro5/allegro_image.h"
#include "allegro5/allegro_native_dialog.h"
#include "ball.h"
#include "ai_paddle.h"
#include <iostream>

using namespace std;

const float FPS = 60;

const int BOUNCER_SIZE = 32;
enum MYKEYS { KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT };

int main(int argc, char** argv)
{
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE* event_queue = NULL;
	ALLEGRO_TIMER* timer = NULL;
	bool redraw = true;
	bool doexit = false;
	bool key[4] = {false, false, false, false };
	ALLEGRO_KEYBOARD_STATE keyState;

	if(!al_init()) {
			fprintf(stderr, "failed to initialize!");
		return -1;
	}

	if(!al_init_image_addon()) {
      al_show_native_message_box(display, "Error", "Error", "Failed to initialize al_init_image_addon!", 
                                 NULL, ALLEGRO_MESSAGEBOX_ERROR);
      return 0;
   }

	if(!al_install_keyboard()) {
		fprintf(stderr, "failed to initialize keyboard!");
		return -1;
	}

	timer = al_create_timer(1.0/FPS);
	if(!timer) {
		fprintf(stderr, "failed to initialize timer!");
		return -1;
	}

	display = al_create_display(SCREEN_WIDTH, SCREEN_HEIGHT);
	if(!display) {
		fprintf(stderr, "display failed to initialize!");
		return -1;
	}

	 event_queue = al_create_event_queue();
   if(!event_queue) {
      fprintf(stderr, "failed to create event_queue!\n");
      al_destroy_display(display);
      al_destroy_timer(timer);
      return -1;
   }

	Paddle paddle;
	if ( !paddle.init() ) {
		cout<<"error";
		return -1;
	}
	 
	Ball ball;
	if ( !ball.init() ) {
		return -1;
	}

	AiPaddle aipaddle;
	if( !aipaddle.init() ) {
		return -1;
	}

	al_register_event_source(event_queue, al_get_display_event_source(display));
 
	al_register_event_source(event_queue, al_get_timer_event_source(timer));
 
	al_register_event_source(event_queue, al_get_keyboard_event_source());
 
	al_clear_to_color(al_map_rgb(0,0,0));
 
	al_flip_display(); 
	
	al_start_timer(timer);

	while(!doexit) {
		ALLEGRO_EVENT ev;

		al_wait_for_event(event_queue, &ev);

		if ( ev.type == ALLEGRO_EVENT_TIMER ) {
			al_get_keyboard_state(&keyState);
			paddle.move(&keyState);
			ball.update(&paddle, &aipaddle);
			aipaddle.update( ball.getVelocity(), ball.getPosition() );
			redraw = true;
		} else if ( ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE ) {
			break;
		} else if(ev.type == ALLEGRO_EVENT_KEY_UP) {
			switch(ev.keyboard.keycode) {
				case ALLEGRO_KEY_ESCAPE:
					doexit = true;
					break;
			}
		}
		 
		if(redraw && al_is_event_queue_empty(event_queue)) {
			redraw = false;
 			al_clear_to_color(al_map_rgb(0,0,0));
			ball.draw();
			paddle.draw();
			aipaddle.draw();
			al_flip_display();
		}
	}

	return 0;
}

 

Along with these, i created a global header file, in which i put common structs:

#ifndef GLOBAL_H
#define GLOBAL_H


#include "allegro5/allegro.h"
#include "allegro5/allegro_image.h"

struct Position {
	float x;
	float y;
};

struct Velocity {
	float x;
	float y;
};

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480

#endif

 

The problem is, sometimes the ball goes through the AI paddle, dont seem to get it why. 

Other issue is, sometimes the ball collides the player paddle but it just doesn't change the direction. It would be helpful if you could point out the error or where I'm going wrong.

 

Thank you!

0

Share this post


Link to post
Share on other sites

The reason the ball sometimes passes through the AI paddle is that you update its position after you've checked for collisions. Move the aipaddle.update() call to prior to the ball.update() call to remedy this, although it still might not register: I think if the combined speed between the ball and the paddle are greater than the paddle's bounding box width, the ball can potentially pass through without the program ever acknowledging it.

 

Quick notes:

- Why are you not using CollisionWithWall?

- Is there any particular reason why the collision detection and input code are in the ball and paddle classes, as opposed to a space of their own?

- You can reduce the amount of duplicate code by having a common base Paddle class both for player controlled and AI controlled paddles.

Edited by Somber
0

Share this post


Link to post
Share on other sites

Generally you want to move objects and then check collision due to the fact that it completely messes up collision resolution if only one object collides with another. Also what you're talking, the ball passing through the paddle is known as tunnelling. Normally that's just a thing related to objects moving faster than the update rate, but part of that I'm sure is caused by the way you're handling collision detection.

 

For your issue with the ball sometimes not reversing direction, taking a wild guess I'd say that happens when the ball moves into a paddle partially and then reverses its velocity and doesn't 'escape' the paddle on the next frame. Generally with collision detection you want to either move an object back to it's previous position when a collision is detected or you want to "nudge" it until it is free from the other object. Only then do you apply things like velocity changes. Unless you want colliding objects to travel through each other, collisions are basically an event that should be reversed in code before they're ever drawn.

 

For fixing tunneling your options are a little limited, you can slow the objects down by capping their velocity, adjust sprite size, change to a continuous form of collision detection, so on. With a game like pong unless you're letting the balls move supersonic speeds or your update rate is extremely low you shouldn't really have an issue.

0

Share this post


Link to post
Share on other sites

The reason the ball sometimes passes through the AI paddle is that you update its position after you've checked for collisions. Move the aipaddle.update() call to prior to the ball.update() call to remedy this, although it still might not register: I think if the combined speed between the ball and the paddle are greater than the paddle's bounding box width, the ball can potentially pass through without the program ever acknowledging it.

 

Quick notes:

- Why are you not using CollisionWithWall?

- Is there any particular reason why the collision detection and input code are in the ball and paddle classes, as opposed to a space of their own?

- You can reduce the amount of duplicate code by having a common base Paddle class both for player controlled and AI controlled paddles.

Thank you for the response :). About the collision detection: I realized it as a function where the ball just checks if it collided with paddles or the wall. Am I wrong in my assumption?

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0