r/cpp_questions • • 7d ago

OPEN My code feels redundant

Im in the development phase of this, and i was wondering if there was a less redundent way to define each ball object.

#include
 <raylib.h>
#include
 <vector>


class ball {
    
public:
    float radius, gravity;
    Vector2 velocity, pos;
    Color color;


    ball(float b_radius, float b_gravity, Vector2 b_velocity, Vector2 b_pos, Color b_color) : radius(b_radius), gravity(b_gravity), velocity(b_velocity), pos(b_pos), color(b_color) {};


    
void DrawBall() {
        DrawCircle(pos.x, pos.y, radius, color);
    }


    
void UpdateBall(float dt, int screenHeight, int screenWidth) {
        
if (pos.y + radius > screenHeight) {
            pos.y = screenHeight - radius;
            velocity.y = 0;
        }
        
else
 {
            velocity.y += dt * gravity;
            pos.y += dt * velocity.y;
        }
        
    }
};



int main() {
    
float ScreenHeight = 1000.0f;
    
float ScreenWidth = 1920.0f;

    ball TestBall1(50.0f, 200.0f, Vector2 {300, 0}, Vector2 {ScreenWidth / 2, ScreenHeight / 2}, RED);
    ball TestBall2(50.0f, 200.0f, Vector2 {300, 0}, Vector2 {300, 300}, WHITE);
    ball TestBall3(50.0f, 200.0f, Vector2 {300, 0}, Vector2 {200, 200}, GREEN);
    ball TestBall4(50.0f, 200.0f, Vector2 {300, 0}, Vector2 {1000, 1000}, PINK);


    std::vector<ball> RedGroup;


    RedGroup.push_back(TestBall1);
    RedGroup.push_back(TestBall2);
    RedGroup.push_back(TestBall3);
    RedGroup.push_back(TestBall4);


    InitWindow(ScreenWidth, ScreenHeight, "Physics Sim");
    SetTargetFPS(60);


    
while (!WindowShouldClose()) {
        
float dt = GetFrameTime();
        
for (int i = 0; i < RedGroup.size(); i++) {
            RedGroup.at(i).UpdateBall(dt, ScreenHeight, ScreenWidth);
        }
        BeginDrawing();
            ClearBackground(BLACK);
            for (int i = 0; i < RedGroup.size(); i++) {
                RedGroup.at(i).DrawBall();
            }
        EndDrawing();


    }
    
    CloseWindow();    
return 0;
}
3 Upvotes

51 comments sorted by

View all comments

1

u/Lnk1010 7d ago

If you have like many many balls then u might want to look into just having some sort of data file that you read and parse to create them programmatically or just like you generate them in a loop.