I am new to programming in the C language. I just decided to pick it up for fun; I have hobbyist experience in Javascript, Java, and a few other languages. For whatever reason, I decided to learn C in the context of developing a program for the Gameboy Classic. So I installed the GBDK, which I understand is outdated. It comes with an LCC compiler. I use VisualBoy Advance to emulate my program.
I am trying to create a simple Breakout clone. So far, I have successfully programmed the paddle with user input. However, I've run into a problem with the ball: it isn't checking for a collision with the paddle. After doing tons of tests, research, and asking around on other sites, I still cannot resolve this problem.
Here is the complete code:
#include <gb/gb.h>
#include "Sprites/paddle.c"
#include "Sprites/ball.c"
int paddleX = 72;
int paddleY = 136;
int paddleSpeed = 1;
int ballAngle = 270;
int ballX = 84;
int ballY = 75;
void setSprites() {
SPRITES_8x8;
//paddle////////////////////////////
set_sprite_data(0, 4, paddle);
set_sprite_tile(0, 0);
move_sprite(0, paddleX, paddleY);
set_sprite_tile(1, 1);
move_sprite(1, paddleX+8, paddleY);
set_sprite_tile(2, 2);
move_sprite(2, paddleX+16, paddleY);
set_sprite_tile(3, 3);
move_sprite(3, paddleX+24, paddleY);
//ball////////////////////////////////
set_sprite_data(4, 1, ball);
set_sprite_tile(4, 4);
move_sprite(4, ballX, ballY);
SHOW_SPRITES;
}
void movePaddle() {
if(joypad() == J_LEFT) {
if(paddleX <= 8) {
paddleX = 8;
}
else {
paddleX -= 1;
}
}
if(joypad() == J_RIGHT) {
if(paddleX >= 136) {
paddleX = 136;
}
else {
paddleX += 1;
}
}
move_sprite(0, paddleX, paddleY);
move_sprite(1, paddleX+8, paddleY);
move_sprite(2, paddleX+16, paddleY);
move_sprite(3, paddleX+24, paddleY);
}
void moveBall() {
if(ballAngle == 270) {
if((ballY >= paddleY-8) && (ballX >= paddleX-8) && (ballX <=
paddleX+24)) {
ballAngle = 90;
}
else {
ballY += 1;
}
}
if(ballAngle == 90) {
ballY -= 1;
}
move_sprite(4, ballX, ballY);
}
void main() {
setSprites();
while(1) {
movePaddle();
moveBall();
delay(20);
}
}
The problem rests within one "if statement." Specifically, the:
if((ballY >= paddleY-8) && (ballX >= paddleX-8) && (ballX <=
paddleX+24)) {
condition. It's just not working. I swapped in a test variable that wasn't changed at all during the rest of the program; FAIL. The only way it works is if I hardcode a value (96, for example). However, that is obviously bad because it wouldn't change whenever the paddle moves.
I am completely stumped on this problem. I am new to C, but this seems like a simple thing. Is my compiler broken? Am I doing something unintentionally wrong? Keep in mind that this is designed with the Gameboy Dev Kit, emulated as a classic Gameboy game.
Any help is appreciated. Thanks!
SOLVED: Strange solution. Instead of adding 24 to paddleX
, I subtract -24. For whatever reason, that works as intended.