From 55137493175f9933b6c75cb592a1eb53bbc68abd Mon Sep 17 00:00:00 2001 From: Alex_jzr Date: Wed, 18 Feb 2026 19:02:12 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ball.c | 158 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 ball.c diff --git a/ball.c b/ball.c new file mode 100644 index 0000000..baec465 --- /dev/null +++ b/ball.c @@ -0,0 +1,158 @@ +#include "raylib.h" +#include + +#define WIDTH 1000 +#define HIGHT 600 + +#define NUM_BALL 15 + +#define R 30 + + +typedef struct{ + float x, y, r, vx, vy; +}Ball; + + +void DrawBall(Ball *ball){ + + DrawCircle(ball->x,ball->y,ball->r,WHITE); + +} + +void Updateing(Ball *ball){ + ball->x += ball->vx; + ball->y += ball->vy; + + +} + +void ElasticCollision(Ball* ball1, Ball* ball2) { + double dx = ball2->x - ball1->x; + double dy = ball2->y - ball1->y; + + double dvx = ball2->vx - ball1->vx; + double dvy = ball2->vy - ball1->vy; + + double dot_product = dx * dvx + dy * dvy; + + if (dot_product >= 0) { + return; + } + + double distance_squared = dx * dx + dy * dy; + + if (distance_squared < 1e-10) { + return; + } + + double factor = dot_product / distance_squared; + + double v1x_new = ball1->vx + factor * dx; + double v1y_new = ball1->vy + factor * dy; + double v2x_new = ball2->vx - factor * dx; + double v2y_new = ball2->vy - factor * dy; + + ball1->vx = v1x_new; + ball1->vy = v1y_new; + ball2->vx = v2x_new; + ball2->vy = v2y_new; +} + +void CollidesWalls(Ball *ball){ + if (ball->x - ball->r <= 0){ + ball->x = ball->r; + ball->vx = -ball->vx; + } + + if (ball->x + ball->r >= WIDTH){ + ball->x = WIDTH - ball->r; + ball->vx = -ball->vx; + + } + + if (ball->y - ball->r <= 0){ + ball->y = ball->r; + ball->vy = -ball->vy; + } + + if (ball->y + ball->r >= HIGHT){ + ball->y = HIGHT - ball->r; + ball->vy = -ball->vy; + } +} + +void CollidesBalls(Ball *currentball,Ball balls[]){ + + for (int i = 0;ix, currentball->y}; + Vector2 c2 = {otherball->x, otherball->y}; + + if (CheckCollisionCircles(c1, currentball->r, c2, otherball->r)){ + + ElasticCollision(currentball,otherball); + + } + + } + +} + + + +void DrawBalls(Ball balls[]){ + for (int i = 0;i