For your code:
What is
top
and
bot
?
Why is
x
and
y
set to 0 for
top
?
I also see some undefined values - for example where is
batr.y
?
You should make some fixed vector position (x,y) = (0,0) for example left bottom corner of your window and make all "pixel" coordinates (that you will ever define) relative to this position.
I would do something like this: (not actual code - just a hint)
Considering that everithing is some sort of rectangle (even the ball).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class Obstacle
{
public:
Obstacle(int x, int y, int width, int height); //Constructor
//For comparison of collision - overload operator==
//If colision occurs then True else False
bool operator==(const Obstacle& secondObstacle);
private:
Obstacle(); //Block default constructor from public access - not entirely needed
int x; //you can measure distance in pixels so int is better than double - my opinion
int y;
int width;
int height;
};
int main()
{
Obstacle leftBar(int numbers for x, y, width, height);
Obstacle rightBar(again 4 int numbers...);
Obstacle ball(4 int numbers...);
while(true){
if(leftBar == ball) //Left bar is colliding with the ball
//... Do stuff
else if(rightBar == ball) //Right bar is colliding with the ball
//... Do some other stuff
else //No collision
//... Continue game or check for game exit and break infinite while loop
}
//You could also check (leftBar == rightBar) but that case should never happen
//At least in classic Pong :-)
}
|
Then content of overloaded
operator==
would be something like this:
(different bounds may be set by different <, >, <=, >=; it's all up to your preferences)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
bool Obstacle::operator==(const Obstacle& secondObstacle)
{
//"this" means left hand side of operator ==. So "a==b" meand that "this" is "a"
//Probably you don't even need to write words "this" in the first time
if (this.x < secondObstacle.x &&
(this.x+this.width) > secondObstacle.x && //X coordinate checked
this.y < secondObstacle.y &&
(this.y+this.height) > secondObstacle.y) //Y coordinate checked
return true; //We have collision
//Now we checked secondObstacle corned at coordinates (X,Y)
else if(this.x < (secondObstacle.x + secondObstacle.width) &&
//... Other checks for other corners of secondObstacle
//... I don't really want to write it all
//... We have corners secondObject-> (x,y), (x+width,y), (x, y+height), (x+w, y+h)
else
return false; //No collision
}
|
You may also include several checks if for example is one object Obstacle inside the other one. "secondObstacle" can be bigger that "this" and the code I posted only checks if some corner of "secondObstacle" is inside of "this" object (left hand side argument of ==).
I hope I didn't make it too confusing. If you didn't get some part from this code snippet just ask.