C语言案例:碰撞反弹小球

生成多个小球,在碰到边界时反弹,本来想设置随机角度,按角度去运行,但试验效果不好,就以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语言案例:碰撞反弹小球

关注公众号 "字节航海家" 及时获取最新内容

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值