用Processing實現了背景滾動、雙向柱子與邊緣碰撞檢測。
效果圖:
- 全局變量部分
PImage brid[]; //鳥動畫幀 圖片
PImage pipe_down; // 管道1 圖片
PImage pipe_up; // 管道2 圖片
PImage background; // 背景 圖片
PImage gameover; // 遊戲結束 圖片
int brid_point = 0; // 鳥動畫當前幀率
float brid_speed = 0; //鳥的速度
float brid_x = 0; // 鳥的位置X
float brid_y = 0; // 鳥的位置Y
int background_pos = 0; // 背景X軸
int pipe_gap = 100; // 管道之間的空隙大小
int pipe_up_random = 0; // 管道位置縮減值
float pipe_down_x = 0; // 隨機管道1的X軸座標
float pipe_down_y = 0; // 隨機管道1的y軸座標
float pipe_up_x = 0; // 隨機管道2的X軸座標
float pipe_up_y = 0; // 隨機管道2的X軸座標
- 啓動函數
void setup() {
size(288, 512, P2D);
brid = new PImage[3];
brid[0] = loadImage("flappybird/bird0_0.png");
brid[1] = loadImage("flappybird/bird0_1.png");
brid[2] = loadImage("flappybird/bird0_2.png");
pipe_down = loadImage("flappybird/pipe_down.png");
pipe_up = loadImage("flappybird/pipe_up.png");
gameover = loadImage("flappybird/text_game_over.png");
background = loadImage("flappybird/bg_day.png");
background_loop();
pipe_loop();
brid_fly();
brid_speed_con();
}
- 繪畫函數
void draw() {
if (frameCount % 5 == 0) {
if (impact_checking()) {
background_loop();
pipe_loop();
brid_fly();
brid_speed_con();
}else{
gameover_show();
}
}
}
- 鼠標事件
void mousePressed() {
brid_speed -=15;
}
- 背景滾動
void background_loop() {
image(background, background_pos, 0);
image(background, background_pos + width, 0);
background_pos -=5;
background_pos %= width;
}
- 管道滾動
void pipe_loop() {
if (background_pos >= -5) {
pipe_up_random = int(random(0, 150));
}
pipe_down_x = width + background_pos;
pipe_down_y = height/2 + pipe_up_random - pipe_up.height - pipe_gap;
pipe_up_x = width + background_pos;
pipe_up_y = height/2 + pipe_up_random;
image(pipe_up, pipe_up_x, pipe_up_y);
image(pipe_down, pipe_down_x, pipe_down_y);
}
- 鳥
void brid_fly() {
brid_x = width/2 - brid[brid_point].width / 2;
brid_y = height/2 - brid[brid_point].height / 2 + brid_speed;
image(brid[brid_point], brid_x, brid_y);
brid_point++;
brid_point %= brid.length;
}
void brid_speed_con() {
brid_speed += 5;
// QQ:1130459060 感興趣的小夥伴加我一起學Processing
}
- 碰撞檢測
boolean impact_checking() {
float real_brid_y = brid_y + brid[0].height - 10;
float real_brid_x = brid_x + brid[0].width - 10;
if (real_brid_y > height || brid_y + 10 < 0) {
return false;
}
if (real_brid_y >= pipe_up_y && (real_brid_x >= pipe_up_x && real_brid_x <= pipe_up_x + pipe_up.width)){
return false;
}
if (real_brid_y <= pipe_down_y + pipe_down.height + brid[0].height / 2 && (real_brid_x >= pipe_down_x && real_brid_x <= pipe_down_x + pipe_down.width)){
return false;
}
return true;
}
- 遊戲失敗
void gameover_show(){
image(gameover, width/2 - gameover.width/2, height/2 - gameover.height/2);
}