我想然让障碍物由上下向中间生长,中间留一条通路
时间: 2023-10-29 10:04:20 浏览: 16
要让障碍物由上下向中间生长,你可以按以下步骤修改代码:
1. 修改 Obstacle 类的构造函数,增加一个参数 isTop,表示当前障碍物是否在通路的上方。代码如下:
```
Obstacle(float x_, float y_, float w_, float h_, float s_, boolean isTop_) {
x = x_;
y = y_;
width = w_;
height = h_;
speed = s_;
isTop = isTop_;
}
```
2. 修改 generateObstacle() 函数,根据 isTop 参数生成障碍物。代码如下:
```
void generateObstacle() {
float obstacle_height = random(obstacle_min_height, obstacle_max_height);
float obstacle_width = random(obstacle_min_width, obstacle_max_width);
float obstacle_gap_y = random(100, height - obstacle_height - 100); // 通路的高度为 100
float obstacle_top_y = 0;
float obstacle_bottom_y = obstacle_gap_y + 100; // 通路的高度为 100
float obstacle_x = width;
obstacles.add(new Obstacle(obstacle_x, obstacle_top_y, obstacle_width, obstacle_height, obstacle_speed, true)); // 上方的障碍物
obstacles.add(new Obstacle(obstacle_x, obstacle_bottom_y, obstacle_width, height - obstacle_bottom_y, obstacle_speed, false)); // 下方的障碍物
}
```
3. 修改 Obstacle 类的 draw() 方法,根据 isTop 参数绘制障碍物。代码如下:
```
void draw() {
noStroke();
if (isTop) {
fill(293, 224, 225); // 上方障碍物的颜色
rect(x, y, width, height);
} else {
fill(293, 224, 225); // 下方障碍物的颜色
rect(x, y, width, height);
}
}
```
4. 修改 Obstacle 类的 update() 方法,根据 isTop 参数更新障碍物的位置。代码如下:
```
void update() {
x -= speed;
if (isTop) {
y += speed;
} else {
y -= speed;
}
}
```
这样一来,障碍物就会从上下两边向中间生长,并留有一条通路。你可以根据需要修改通路的高度和障碍物的颜色、大小和速度等参数。