生成多个小球,在碰到边界时反弹,本来想设置随机角度,按角度去运行,但试验效果不好,就以xy轴相同距离运行。
项目需要用到图形库,参考: Dev C++ 中添加Easy Graphics Engine
案例效果
程序代码
#include <stdio.h>
#include <math.h>
#include <graphics.h>
#define LEN(array) (sizeof(array) / sizeof(array[0]))
struct Circle
{
float x, y; // 圆心坐标
float moveX, moveY;
int radius; // 半径
float angle;
int speed;
color_t color;
};
void calculate_ball_location(struct Circle *cir, int *winWidth, int *winHeight)
{
// RIGHT
if (cir->x + cir->radius * 2 >= *winWidth)
{
cir->angle = 0.5 * PI - cir->angle;
cir->x = *winWidth - cir->radius * 2;
cir->moveX = -cir->moveX;
}
// LEFT
if (cir->x <= 0)
{
cir->angle = 0.5 * PI - cir->angle;
cir->moveX = -cir->moveX;
cir->x = 0;
}
// TOP
if (cir->y <= 0)
{
cir->angle = 0.5 * PI - cir->angle;
cir->moveY = -cir->moveY;
cir->y = 0;
printf("top");
}
// BOTTOM
if (cir->y + cir->radius * 2 >= *winHeight)
{
cir->angle = 0.5 * PI - cir->angle;
cir->moveY = -cir->moveY;
cir->y = *winHeight - cir->radius * 2;
}
// 以指定角度运行效果不好
// cir.x += cir.speed * cos(cir.angle)*moveX;
// cir.y += cir.speed * sin(cir.angle)*moveY;
cir->x += cir->speed * cir->moveX;
cir->y += cir->speed * cir->moveY;
}
int main()
{
// 初始化绘图窗口
int winWidth = 640, winHeight = 480;
initgraph(winWidth, winHeight, INIT_RENDERMANUAL | INIT_NOFORCEEXIT);
// 设置背景色并修改背景
setbkcolor(BLACK);
const float PI = 3.1415926;
Circle cirs[20];
int len = LEN(lines);
for (int i = 0; i < len; i++)
{
int radius = rand() % 25;
int speed = rand() % 25;
float angle = PI / (rand() % 2 + 8);
float locationX = rand() % 600 + 20;
float locationY = rand() % 440 + 20;
color_t color = EGEARGB(rand() % 255, rand() % 255, rand() % 255, 89);
struct Circle cir = {locationX, locationY, 1.0, 1.0, radius, angle, speed, color};
cirs[i] = cir;
}
for (; is_run(); delay_fps(32))
{
// 清屏
cleardevice();
for (int i = 0; i < len; i++)
{
// 画圆
calculate_ball_location(&cirs[i], &winWidth, &winHeight);
setfillcolor(cirs[i].color);
ege_fillellipse(cirs[i].x, cirs[i].y, 2 * cirs[i].radius, 2 * cirs[i].radius);
}
}
closegraph();
return 0;
}
查看原文:C语言案例:碰撞反弹小球
关注公众号 "字节航海家" 及时获取最新内容