C语言Plus 2020-04-06
生命太短暂,不要去做一些根本没有人想要的东西。
不要强迫别人拥有勇气,你行你上
题目:用easyx演示小球边界碰撞解析:看代码~
实例
#include<stdio.h>
#include<graphics.h>
#include<stdlib.h>
#include<Windows.h>
//小球结构体
struct Balloon
{
int x; //横坐标
int y; //纵坐标
int r; //半径
int vx; //x轴速度分量
int vy; //y轴速度分量
}ball;
//移动小球
void move()
{
ball.x += ball.vx;
ball.y += ball.vy;
}
//判断碰撞
void jude()
{
int temp = ball.r+5;
if (ball.x + temp >= 640 || ball.x - temp <= 0)//①
{
if (ball.y + temp >= 480 || ball.y - temp <= 0)//②
{
//①②同时成立,则小球撞到角落,x,y分量都要取反
ball.vx= -ball.vx;
ball.vy= -ball.vy;
}
else
{
//只有①成立,则小球撞到左右边界,x分量取反
ball.vx = -ball.vx;
}
}
if (ball.y + temp >= 480 || ball.y - temp <= 0) //③
{
//只有③成立,则小球撞到上下边界,y分量取反
ball.vy = -ball.vy;
}
}
int main()
{
initgraph(640, 480);
srand(GetTickCount());
ball.x = rand() % 32*20; //随机产生20的倍数的坐标
ball.y = rand() % 12*20;
ball.r = 20;
ball.vx = 20 ;
ball.vy = 20;
DWORD t1, t2;
t2=t1 = GetTickCount();//获取系统开机到现在所经过的毫秒数
setbkcolor(WHITE);
while (1)
{
BeginBatchDraw();//XX
cleardevice();
setfillcolor(BLUE);
fillcircle(ball.x, ball.y, ball.r);
jude();
if (t2 - t1 > 100)
{//微信公众号:C语言Plus
move();
t1 = t2;
}
t2 = GetTickCount();
EndBatchDraw();//OO
//XXOO两步是双缓冲绘图,让界面看起来不卡
}
return 0;
}