返回

打造你的第一款flutter小恐龙游戏:加入障碍物,让游戏更具挑战!

见解分享

在之前的文章中,我们已经完成了小恐龙的移动和跳跃功能。现在,我们将添加障碍物,让游戏更具挑战性和趣味性。

首先,我们需要定义一个障碍物类。这个类将包含障碍物的位置、大小和速度等属性。我们还可以为障碍物添加一个动画,让它在屏幕上移动。

class Obstacle {
  double x;
  double y;
  double width;
  double height;
  double speed;
  Animation<double> animation;

  Obstacle({
    required this.x,
    required this.y,
    required this.width,
    required this.height,
    required this.speed,
    required this.animation,
  });
}

接下来,我们需要在游戏中添加障碍物。我们可以通过在游戏循环中生成障碍物来做到这一点。

void generateObstacles() {
  if (Time.time > _lastObstacleTime + _obstacleFrequency) {
    _lastObstacleTime = Time.time;

    double x = _screenWidth;
    double y = _screenHeight - _groundHeight - _obstacleHeight;
    double width = _obstacleWidth;
    double height = _obstacleHeight;
    double speed = _obstacleSpeed;
    Animation<double> animation = _obstacleAnimation;

    Obstacle obstacle = Obstacle(
      x: x,
      y: y,
      width: width,
      height: height,
      speed: speed,
      animation: animation,
    );

    _obstacles.add(obstacle);
  }
}

最后,我们需要处理障碍物与小恐龙的碰撞。如果小恐龙与障碍物发生碰撞,那么游戏就结束了。

void checkCollisions() {
  for (Obstacle obstacle in _obstacles) {
    if (obstacle.x < _trex.x + _trex.width &&
        obstacle.x + obstacle.width > _trex.x &&
        obstacle.y < _trex.y + _trex.height &&
        obstacle.y + obstacle.height > _trex.y) {
      _gameOver = true;
    }
  }
}

现在,我们就完成了小恐龙游戏的障碍物功能。您可以运行游戏,体验一下游戏的新玩法。

在下一篇教程中,我们将介绍如何为游戏添加声音效果和背景音乐,让游戏更加生动有趣。