Search⌘ K
AI Features

Creating Obstacles

Explore how to design and implement obstacles in a Rust-based game. Learn to create obstacle structures with random gaps, render walls on screen, and detect collisions with the player to enhance game interaction.

We'll cover the following...

The other key objective of Flappy Dragon is dodging obstacles. Let’s add walls to the game, with gaps that the dragon can fly through. Begin by adding another struct to the program:

Rust 1.40.0
struct Obstacle {
x: i32,
gap_y: i32,
size: i32
}

Obstacles have an x value, defining their position in world-space (to match the player’s world-space x value). The gap_y variable defines the center of the gap through which the dragon may pass. size defines the length of the gap in the obstacle.

We’ll need to define a constructor for the obstacle:

Rust 1.40.0
impl Obstacle {
fn new(x: i32, score: i32) -> Self {
let mut random = RandomNumberGenerator::new();
Obstacle {
x,
gap_y: random.range(10, 40),
size: i32::max(2, 20 - score)
}
}

Computers aren’t great at generating genuinely random numbers. There are many algorithms for generating pseudo-random numbers, though. Thankfully, bracket-lib includes one called xorshift, wrapped in convenient access functions.

The constructor creates a new RandomNumberGenerator and uses it to place the obstacle at ...