I am creating a game using SDL2 which creates 200 objects of a class Star
and prints onto the screen all 200 as 2px x 2px rects in random locations. I created a player class which creates a 10px x 10px rect that can be moved using WASD.
I created a vector of type Star which holds all 200 stars with identifier allStars
.
The game loop runs three functions: Event()
, Update()
, and Render()
. In Event()
, there is a piece of code which intitiates a for loop which iterates through allStars
checks first to see whether the x-coordinate of the star matches with that of the player box, and second checks to see if the y-coordinate matches with the player box.
else if (state[SDL_SCANCODE_SPACE]) {
for (int i = 0; i < allStars.size(); i++) {
if (allStars[i].starPosX > player.rect.x && allStars[i].starPosX < (player.rect.x + player.rect.w)) {
if (allStars[i].starPosY > player.rect.y && allStars[i].starPosY < (player.rect.y + player.rect.h)) {
std::cout << allStarsNames[i] << ": " << allStars[i].starPosX << ", " << allStars[i].starPosY << ", " << allStars[i].starColor << ", " << allStars[i].starMass << "\n";
std::cout << "\n\n";
}
}
}
}
starPosX
and starPosY
are attributes of the Star
class which are used to give value to the x- and y-coordinates of the rect which is created for the star.
I was attempting to see if the program would print information about the star when this code was run in order to check if it was working, however the information of the star is never printed. I can't seem to find a correct method of creating a hitbox for a rect in SDL2. Is there a procedure I could use to solve this issue?
So far I have made adjustsments to the rect in the player class and how I have referred to its position. This can be seen in how I have wrote player.rect.x
, whereas previously I had referred to another attribute of the Player
class, playerX
and playerY
. My reasoning for creating so many versions of the x- and y-coordinates was from avoiding a whole other problem entirely. The Player
class is as follows:
class Player {
public:
int playerX = 250;
int playerY = 250;
int playerW = 10;
int playerH = 10;
SDL_Rect rect;
Player() {
rect.x = playerX;
rect.y = playerY;
rect.w = playerW;
rect.h = playerH;
}
void UpdatePlayerPos(SDL_Renderer *renderer) {
rect.x = playerX;
rect.y = playerY;
}
void DrawPlayer(SDL_Renderer *renderer) {
SDL_RenderDrawRect(renderer, &rect);
}
};
The UpdatePlayerPos()
method is called during the Update()
function during the gameloop. It seems that my logic of how to check whether or not two rectangles overlap one another is the logical way to go about it, however I cannot seem to find where the issue is located that causes the print out statement to not execute.