Files
simple_physics/main.c
2025-12-24 14:24:07 +01:00

110 lines
2.3 KiB
C

#include <stddef.h>
#include <raylib.h>
#include <raymath.h>
#include <stdio.h>
#include "objects.h"
struct global {
const int scwidth, scheight;
int fps;
object *objs[128];
size_t obj_count;
double terminal_v;
};
struct global gl = {1600, 900, 144, {}, 0, 15};
void addobj(object *obj)
{
gl.objs[gl.obj_count++] = obj;
}
void drawobjs()
{
for (int i = 0; i < gl.obj_count; i++)
{
object *obj = gl.objs[i];
DrawSphere(obj->pos, obj->r, obj->color);
}
}
void updateobjs()
{
for (int i = 0; i < gl.obj_count; i++)
{
object *obj = gl.objs[i];
obj->vel.y -= 0 * GetFrameTime();
//if (obj->vel.y < gl.terminal_yv)
if (obj->pos.y < obj->r) {
obj->pos.y = obj->r;
obj->vel.y *= -obj->restitution;
}
for (int j = 0; j < gl.obj_count; j++)
{
if (i==j) continue;
object *obj2 = gl.objs[j];
integrate_g(obj, obj2, gravitation_force(obj, obj2));
//float min_dist_delta = Vector3Distance(obj->pos, obj2->pos) - (obj->r+obj2->r);
//if (min_dist_delta < 0)
//{
// Vector3SubtractValue(obj->pos, min_dist_delta);
//}
if (Vector3Distance(obj->pos, obj2->pos) < obj->r+obj2->r+0.01f)
{
resolve_collision(obj, obj2);
}
}
float ratio_speed_to_terminal = Vector3Length(obj->vel)/gl.terminal_v;
if (Vector3Length(obj->vel) > gl.terminal_v)
{
obj->vel = Vector3Scale(obj->vel, 1.0f/ratio_speed_to_terminal);
}
DrawLine3D(obj->pos, Vector3Add(obj->pos, obj->vel), GREEN);
obj->pos = Vector3Add(obj->pos, Vector3Scale(obj->vel, GetFrameTime()));
}
}
void freeobjs()
{
for (int i = 0; i < gl.obj_count; i++)
{
object *obj = gl.objs[i];
free(obj);
}
}
int main(void) {
InitWindow(gl.scwidth, gl.scheight, "raylib engine");
SetTargetFPS(gl.fps);
addobj(newobj((Vector3){0, 20, 0}, 1, RED, 1, 1000));
addobj(newobj((Vector3){8, 20, 0}, 2, BLUE, 1, 2000));
gl.objs[1]->vel = (Vector3){0, 0, 0};
Camera3D camera = {{0, 20, -30}, {0, 0, 0}, {0, 1, 0}, 45, CAMERA_PERSPECTIVE};
DisableCursor();
while(!WindowShouldClose())
{
UpdateCamera(&camera, CAMERA_FREE);
BeginDrawing();
{
ClearBackground(BLACK);
BeginMode3D(camera);
DrawPlane((Vector3){0, 0, 0}, (Vector2){500, 500}, RAYWHITE);
updateobjs();
drawobjs();
EndMode3D();
}
EndDrawing();
}
freeobjs();
CloseWindow();
return 0;
}