physics/BouncyBlock1D.hpp
2024-12-10 20:23:03 +01:00

77 lines
2.1 KiB
C++

#ifndef PHYSICS_HEADER
#define PHYSICS_HEADER
/* A red cube which can only move horizontally and is mode of rubber.
*/
class Block1D {
public:
// Block properties
const int block_size = 30;
const int guard_size = 10;
const float restitution = 0.72f;
// Movement bounds
const float min_x = screenWidth/10;
const float max_x = screenWidth-(screenWidth/10);
// Movement state
Vector2 position = {min_x, screenHeight/2};
Vector2 direction = {0, 0};
float speed = 0;
double last_update;
// ---
void display(void) {
/* Guard line top
* Block
* Guard line bottom
*/
DrawRectangle(min_x, position.y-guard_size, max_x-min_x, guard_size, GRAY);
DrawRectangle(position.x, position.y, block_size, block_size, RED);
DrawRectangle(min_x, position.y+block_size, max_x-min_x, guard_size, GRAY);
// Hud
DrawText(TextFormat("X: %5.2f", position.x), 10, 10, 20, DARKGRAY);
DrawText(TextFormat("Y: %5.2f", position.y), 10, 40, 20, DARKGRAY);
DrawText(TextFormat("Speed: %5.2f", speed), 10, 70, 20, DARKGRAY);
}
void control(Vector2 click) {
direction = diff(click, position);
speed += abs(direction.x);
direction = (Vector2) {
.x = signum(direction.x),
.y = 0,
};
}
void update(void) {
double update_time = GetTime();
float delta = speed * (update_time - last_update) * direction.x;
if (position.x + delta < min_x) {
position.x = min_x;
speed = speed * restitution;
direction.x = direction.x * -1;
} else
if (position.x + delta > (max_x-block_size)) {
position.x = max_x-block_size;
speed = speed * restitution;
direction.x = direction.x * -1;
} else {
position.x += speed * (update_time - last_update) * direction.x;
if (speed - 1.1f > 0) {
speed -= 1.1f;
} else {
speed = 0;
}
}
last_update = update_time;
}
} content;
#endif