动画的斜线运动 | 轻流扇
0%

动画的斜线运动

基于easyx库的斜线动画实现

preface: 如下

简单来说,重点在于下面的 跳出循环条件十分的巧妙。这样保证了某物品能够到达指定的坐标,定义的移动分量是根据float来计算的,当然也可以换种思路,即currentX = x1 + (int) dx*n dx为每次移动的分量,最后加个跳出循环条件。

这种比我最早想到的单纯的for循环,更加方便实用。

1
2
3
4
5
if (remainDist <= speed)
{
putimage(x2, y2, pImg); // 在终点显示图像
break;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <graphics.h>
#include <conio.h>
#include <math.h>

// 斜线动画函数
// 参数:起点坐标(x1,y1),终点坐标(x2,y2),动画速度speed,图像指针pImg
void DiagonalAnimation(int x1, int y1, int x2, int y2, int speed, IMAGE* pImg)
{
// 计算两点之间的距离
float dx = x2 - x1;
float dy = y2 - y1;
float distance = sqrt(dx * dx + dy * dy);

// 计算单位方向向量
float dirX = dx / distance;
float dirY = dy / distance;

// 当前动画位置
float currentX = x1;
float currentY = y1;

// 动画循环
while (true)
{
// 计算当前位置到终点的距离
float remainDist = sqrt((x2 - currentX) * (x2 - currentX) +
(y2 - currentY) * (y2 - currentY));

// 如果已经到达终点或足够接近
if (remainDist <= speed)
{
putimage(x2, y2, pImg); // 在终点显示图像
break;
}

// 更新位置
currentX += dirX * speed;
currentY += dirY * speed;

// 显示图像
cleardevice();
putimage((int)currentX, (int)currentY, pImg);

// 控制帧率
Sleep(30);
FlushBatchDraw(); // 如果启用了双缓冲
}
}

int main()
{
// 初始化图形窗口
initgraph(800, 600);
BeginBatchDraw(); // 启用双缓冲

// 创建一个简单的图像(红色圆形)作为动画对象
IMAGE img(50, 50);
SetWorkingImage(&img);
setbkcolor(WHITE);
cleardevice();
setfillcolor(RED);
fillcircle(25, 25, 25);
SetWorkingImage(NULL);

// 调用斜线动画函数
DiagonalAnimation(100, 100, 700, 500, 5, &img);

// 关闭图形窗口
EndBatchDraw();
_getch();
closegraph();
return 0;
}

过往:https://zywifeliuying.top/2024/08/05/01/

留下万分之一点,采得孤人所笑言