class Player
{
public:
Player()
{
loadimage(&img_shadow_player, _T("img/shadow_player.png"));
anim_left=new Animation (_T("img/player_left_%d.png"), 6, 45);
anim_right=new Animation (_T("img/player_right_%d.png"), 6, 45);
}
~Player()
{
delete anim_left;
delete anim_right;
}
void ProcessMessage(const ExMessage& msg)
{
if (msg.message == WM_KEYDOWN)
{
switch (msg.vkcode)
{
case VK_UP:
is_up = true;
break;
case VK_DOWN:
is_down = true;
break;
case VK_LEFT:
is_left = true;
turn_left = true;
break;
case VK_RIGHT:
is_right = true;
turn_left = false;
break;
}
}
else if (msg.message == WM_KEYUP)
{
switch (msg.vkcode)
{
case VK_UP:
is_up = false;
break;
case VK_DOWN:
is_down = false;
case VK_LEFT:
is_left = false;
break;
case VK_RIGHT:
is_right = false;
break;
}
}
}
void Move()
{
/*斜着走时会叠加根号二倍,移动速度加快
if (is_up) player_pos.y -= player_speed;
if (is_down) player_pos.y += player_speed;
if (is_left) player_pos.x -= player_speed;
if (is_right) player_pos.x += player_speed;*/
//移动优化
int dir_x = is_right - is_left;//向右则dir_x为正,向左则为负
int dir_y = is_down - is_up;
double len_dir = sqrt(dir_x * dir_x + dir_y * dir_y);
if (len_dir != 0)
{
double normalized_x = dir_x / len_dir;//相当于向量
double normalized_y = dir_y / len_dir;
player_pos.x += player_speed * normalized_x;
player_pos.y += player_speed * normalized_y;
}
}
void Draw()
{
//不让派蒙出框
if (player_pos.x < 0) player_pos.x = 0;
if (player_pos.y < 0) player_pos.y = 0;
if (player_pos.x + player_width > width) player_pos.x = width - player_width;
if (player_pos.y + player_height > height) player_pos.y = height - player_height;
putimage_alpha(player_pos.x + 25, player_pos.y + 80, &img_shadow_player);
if (turn_left) anim_left.play();
else anim_right.play();
}
private:
const int player_width = 80;
const int player_height = 80;
POINT player_pos = { 500,500 };
int player_speed = 5;
IMAGE img_shadow_player;
bool is_up = false;
bool is_down = false;
bool is_left = false;
bool is_right = false;
bool turn_left = true;
Animation* anim_left;
Animation* anim_right;
};
class Animation
{
public:
Animation(LPCTSTR path,int num,int interval)
{
interval_ms = interval;
TCHAR path_file[256];
for (size_t i = 0; i < num; i++)
{
_stprintf_s(path_file, path, i);
IMAGE* frame = new IMAGE();
loadimage(frame, path_file);
frame_list.push_back(frame);
}
}
~Animation()
{
for (size_t i = 0; i < frame_list.size(); i++)
delete frame_list[i];
}
void play()
{
timer++;
if (timer > interval_ms)
{
idx_frame = (idx_frame + 1) % frame_list.size();
timer = 0;
}
putimage_alpha(player_pos.x, player_pos.y, frame_list[idx_frame]);
}
private:
int timer = 0;
int idx_frame = 0;
int interval_ms=0;
vector<IMAGE*>frame_list;
};