Processing实现简易的Flappy Brid

用Processing实现了背景滚动、双向柱子与边缘碰撞检测。

效果图:

Processing实现简易的Flappy Brid_第1张图片

  • 全局变量部分
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);
}

 

你可能感兴趣的:(processing)