球碰撞模拟物理效果

通过EasyX实现代码如下:

#include<graphics.h>
#include<conio.h>
#include<time.h>
const int xPosMax(800);//屏幕大小
const int yPosMax(480);
const int R = 30;            //半径
const int BallSpeed(10);
struct Ball    //球
{
	float x, y, vx, vy, ax, ay, lost;
	void Update()
	{
		vx += ax, vy += ay;//更新增量
		x += vx, y += vy;
		if (r.x > xPosMax - R + 1)
			r.x = xPosMax - R,
			r.vx = int(-r.vx*r.lost);//反弹,改变速度方向以及损耗能量
		else if (r.x < R - 1)
			r.x = R, r.vx = int(-r.vx*r.lost);

		if (r.y > yPosMax - R + 1)
			r.y = yPosMax - R,
			r.vy = int(-r.vy*r.lost);
		else if (r.y < R - 1)
			r.y = R, r.vy = int(-r.vy*r.lost);
	}
}r = { R + 30,R + 30,12,0,0,0.95,0.95 };   //地心引力为竖直方向

void RunBall();    //球的运动
void main()     //主函数
{
	initgraph(xPosMax, yPosMax);
	BeginBatchDraw();//开始绘图        用于减轻闪烁
	{
		RunBall();
	}
	EndBatchDraw();//结束绘图
	closegraph();
}
void RunBall()//球的运动
{
	while (1)
	{
		if (_kbhit() && _getch() == 27)
			break;//按esc退出
		setcolor(WHITE);
		circle(int(r.x), int(r.y), R);//绘2d球
		FlushBatchDraw();//执行未完成的绘制任务,这个函数其实可以重载,精确作图
		r.Update();//更新球位置
		Sleep(BallSpeed);
		cleardevice();
	}
}

结果如下:

参考链接:

https://tieba.baidu.com/p/1025218988?red_tag=0355374926

发布了111 篇原创文章 · 获赞 179 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_44350205/article/details/105675024