I have no idea how to explain it, I’m bad at explaining things.
I am trying to make a 2D top-down scrolling game and the hitboxes keep getting stuck inside of each other.
My code:
#include "raylib.h"
#include <stdio.h>
int xadd = 0;
int yadd = 0;
int lastx = 0;
int lasty = 0;
bool collision = false;
class Boxes {
float x;
float y;
int w;
int h;
Rectangle bxrec;
public:
Boxes(float sx, float sy, int sw, int sh) {
x = sx;
y = sy;
w = sw;
h = sh;
bxrec = { x - w/2, y - h/2, w, h };
}
void Update(Rectangle Rect) {
if (IsKeyDown(KEY_W)) {
for (int i = 0; i < 2; i++) {
yadd++;
if (CheckCollisionRecs(bxrec, Rect) || collision) {
collision = true;
yadd = lasty;
}
else {
collision = false;
lasty = yadd;
}
}
}
if (IsKeyDown(KEY_S)) {
for (int i = 0; i < 2; i++) {
yadd--;
if (CheckCollisionRecs(bxrec, Rect) || collision) {
collision = true;
yadd = lasty;
}
else {
collision = false;
lasty = yadd;
}
}
}
bxrec.y = (y+yadd/4) - h / 2;
if (IsKeyDown(KEY_A)) {
for (int i = 0; i < 2; i++) {
xadd++;
if (CheckCollisionRecs(bxrec, Rect) || collision) {
collision = true;
xadd = lastx;
}
else {
collision = false;
lastx = xadd;
}
}
}
if (IsKeyDown(KEY_D)) {
for (int i = 0; i < 2; i++) {
xadd--;
if (CheckCollisionRecs(bxrec, Rect) || collision) {
collision = true;
xadd = lastx;
}
else {
collision = false;
lastx = xadd;
}
}
}
bxrec.x = (x + xadd/4) - w / 2;
}
void Draw() {
DrawRectangleRec(bxrec, RED);
}
};
class Player {
public:
Rectangle Rect = { 640 - 25, 360 - 25, 50, 50 };
Texture2D t2dplayer;
Texture2D flash1;
void Draw() {
DrawTexture(t2dplayer, 640 - 25, 360 - 25, WHITE);
DrawTexture(flash1, 640 - 150, 360 - 150, (Color){ 255, 255, 255, 255 });
DrawRectangleRec(Rect, (Color){ 0, 255, 0, 128 });
}
};
int main() {
const int screenWidth = 1280;
const int screenHeight = 720;
printf("Kindly ignore this terminal please\nThis is just part of the game\nPlease tell the developer if an error pops up here\n");
SetTraceLogLevel(0);
InitWindow(screenWidth, screenHeight, "GAME");
Player player;
Image imgPlayer = LoadImage("resources/Player.png");
ImageResize(&imgPlayer, 50, 50);
player.t2dplayer = LoadTextureFromImage(imgPlayer);
UnloadImage(imgPlayer);
Image imgflash1 = LoadImage("resources/flash1.png");
ImageResize(&imgflash1, 300, 300);
player.flash1 = LoadTextureFromImage(imgflash1);
UnloadImage(imgflash1);
int bxx[4] = { 840, 440, 640, 640 };
int bxy[4] = { 360, 360, 560, 160 };
int bxw[4] = { 10, 10, 400, 400 };
int bxh[4] = { 400, 400, 10, 10 };
Boxes boxes[4] = {{bxx[0],bxy[0],bxw[0],bxh[0]},{bxx[1],bxy[1],bxw[1],bxh[1]},{bxx[2],bxy[2],bxw[2],bxh[2]},{bxx[3],bxy[3],bxw[3],bxh[3]}};
SetTargetFPS(60);
while (!WindowShouldClose()) {
// Update
for (int b = 0; b < 4; b++) {
boxes[b].Update(player.Rect);
}
if (IsKeyPressed(KEY_F)) {
ToggleFullscreen();
}
// Draw
BeginDrawing();
ClearBackground(RAYWHITE);
for (Boxes bo : boxes) {
bo.Draw();
}
player.Draw();
EndDrawing();
}
// De-Initialization
UnloadTexture(player.t2dplayer);
CloseWindow();
return 0;
}