一个简单的飞机大战游戏,但是运行时会很卡,就是移动飞机时会有严重的滞后感。不仅没有按下键盘就移动的感觉,而且在按键盘的上下左右键的时候,整个窗口会很卡(就像小学上微机课打开个浏览器就卡半天的感觉),绘制的飞机图片会在卡的时候直接闪没有。问的chatgpt,说是peekmessage的问题。求大佬看一下怎么解决
#include<iostream>
#include<string.h>
#include<easyx.h>
#pragma comment(lib,"MSIMG32.LIB")
#define SPEED 5
POINT fly_pos{ 150,320 };
inline void putimage_a(int x, int y, IMAGE* img) {
int h = img->getheight();
int w = img->getwidth();
AlphaBlend(GetImageHDC(NULL), x, y, w, h,
GetImageHDC(img), 0, 0, w, h, { AC_SRC_OVER,0,255,AC_SRC_ALPHA });
}
class Fly {
public:
const int fly_width = 90;
const int fly_height = 102;
Fly() {
loadimage(&fly, _T("img/飞机.png"));
}
~Fly() {
}
void getboard(const ExMessage&msg) {
switch (msg.message) {
case WM_KEYDOWN:
switch (msg.vkcode) {
case VK_UP:
is_move_up = true;
break;
case VK_DOWN:
is_move_down = true;
break;
case VK_LEFT:
is_move_left = true;
break;
case VK_RIGHT:
is_move_right = true;
break;
}
break;
case WM_KEYUP:
switch (msg.vkcode) {
case VK_UP:
is_move_up = false;
break;
case VK_DOWN:
is_move_down = false;
break;
case VK_LEFT:
is_move_left = false;
break;
case VK_RIGHT:
is_move_right = false;
break;
}
break;
}
}
void move() {
//实现斜向正向方向的速度一致
putimage_a(position.x, position.y, &fly);
int dir_x = is_move_right - is_move_left;
int dir_y = is_move_down - is_move_up;
double len = sqrt(dir_x * dir_x + dir_y * dir_y);
if (len != 0) {
double re_speed_x = dir_x / len;
double re_speed_y = dir_y / len;
position.x += (int)(re_speed_x * SPEED);
position.y += (int)(re_speed_y * SPEED);
}
//边界情况限制
if (position.x < 0)position.x = 0;
if (position.y < 0)position.y = 0;
if (position.x + fly_w >= 400)position.x = 400 - fly_w;
if (position.y + fly_h >= 640)position.y = 640 - fly_h;
}
const POINT& GetPosition()const {
return position;
}
private:
const int fly_w = 90;
const int fly_h = 102;
private:
IMAGE fly;
POINT position = { 150,320 };
bool is_move_up = false;
bool is_move_down = false;
bool is_move_left = false;
bool is_move_right = false;
};
int main() {
bool running = 1;
IMAGE background;
ExMessage msg;
Fly fly;
initgraph(400, 640);
loadimage(&background, _T("img/背景2.png"));
BeginBatchDraw();
while (running) {
while (peekmessage(&msg)) {
cleardevice();
putimage(0, 0, &background);
fly.getboard(msg);
fly.move();
FlushBatchDraw();
}
EndBatchDraw();
}
getchar();
return 0;
}