After a bit of playing with code, it turns out that the problem is caused by getGObjectAt
. It doesn't return a pointer to your paddle even though it's in the specified location. Rather, it returns NULL
. Below is a short program that verifies that
#include <stdio.h>
#include <math.h>
#include "gwindow.h"
#include "gobjects.h"
int main(void)
{
// create the window
#define WIDTH 400
#define HEIGHT 600
GWindow gw;
gw = newGWindow(WIDTH, HEIGHT);
// create the paddle
GPolygon paddle = newGPolygon();
setLocation(paddle, (WIDTH/2 - 50/2), HEIGHT - 40);
addVertex(paddle, 0, 0);
addEdge(paddle, -20, -10);
addVertex(paddle, -20, -10);
addEdge(paddle, -20, 0);
addVertex(paddle, -40, -10);
addEdge(paddle, -20, 10);
addVertex(paddle, -60, 0);
addEdge(paddle, 60, 0);
add(gw, paddle);
setColor(paddle, "RED");
setFilled(paddle, true);
// get the coordination of the paddle
float paddleX = getX(paddle);
float paddleY = getY(paddle);
printf("x: %.0f\ny: %.0f\n", paddleY, paddleX);
// verify the existence of the paddle using getGObjectAt
if (getGObjectAt(gw, paddleX, paddleY))
printf("found the paddle\n");
else
printf("didn't find the paddle\n");
}
Output:

My suggestion is to write your own version of getGObjectAt
that detects collisions of the ball with the paddle using some calculations and maybe use this function as part of detectCollision
's definition.
For the sake of simplicity, I'll assume my paddle is a GRect
and getGObjectAt
doesn't work for GRect
s, I'd write a function like this to detect collisions of the bottom side of the ball with the top side of my paddle (depending on your approach, you might need your paddle declared as a global variable or to pass an instance of it to the function)
// returns true if bl collides with pdl in gw
bool collidedWithPaddle(GWindow gw, GRect pdl, GOval bl)
{
// calculate paddle coordinates
float pdlX = getX(pdl);
float pdlY = getY(pdl);
// calculate ball coordinates
float blX = getX(bl);
float blY = getY(bl);
/* check whether the bottom side of the ball collides
* with the top side of the paddle */
if (blY + RADIUS >= pdlY)
{
// the right side of the paddle
float pdlR = pdlX + PDL_W;
// the right side of the ball
float blR = blX + RADIUS;
return (blR >= pdlX && blR <= pdlR + RADIUS);
}
return false;
}