Skip to content

Please update your browser

Your browser version is not supported by this site. CS First may not work properly. Learn more

3. Obstacles qui bougent


In this video, you will make an obstacle move across the stage. In the finished game, it will look like the racer is moving to the right. However, the racer stays in place, and only the obstacles move. This creates the illusion that the racer is moving.

First, program the obstacle sprite to start at a random point on the right of the screen.

Select the obstacle sprite. From the "motion" menu, drag out a “go to” block. Type in “240” for the x value in the “go to” block. Click the block to see what happens.

Great! The obstacle moves to the right of the stage, but it always goes to the same spot. To make it go to a random spot on the right side, add a “pick random” block from the “operators” menu, and place it in the y value. Change the values to negative 180 and 180. Click on the block a few times to test it.

Great! Now the obstacle sprite moves up and down to a random spot on the right.

Next, make the obstacle move to the left. From the “control” menu, drag out a “repeat until” block, and add it to the bottom of the block stack. Remember, the “repeat until” block is a loop that repeats the blocks inside it until something specific happens. In this case, the obstacle should repeat moving to the left until it reaches the left edge of the stage. From the “motion” menu, drag out a “change x by” block, and insert it into the “repeat until” loop. Since the sprite needs to move left along the stage’s x axis, change the “10” to “negative 10.”

The loop needs to be able to detect when the obstacle is on the left side of the stage.

The obstacle is on the left when its x position is negative 240. From the “operators” menu, drag out a “less than” block, and add it to the “repeat until” loop. Add an “x position” block from the “motion” menu to the first space. In the second space, type “negative 240.”

This loop now reads “repeat moving negative 10 steps until the sprite’s x position is less than negative 240.” In other words, “repeat moving to the left until the sprite is on the left edge.” Test your code by clicking on these blocks.

Nice! The obstacle starts at a random position on the right and moves towards the left.

Here's the game plan: Make the obstacle sprite go to a random spot on the right using a “go to” block and a “pick random” block.

Next, make the obstacle sprite move left using a “repeat until” loop, a condition, and motion blocks.

In the next video, you’ll program this obstacle to copy itself forever, making more obstacles to avoid.

arrow_backward Retour
Suivant arrow_forward
  1. À l'aide des blocs "Aller à" et "Nombre aléatoire", fais aller le lutin Obstacle à un endroit au hasard sur la droite.
  2. Ensuite, en utilisant une boucle "Répéter jusqu'à", une condition et des blocs "Mouvement", fais avancer le lutin Obstacle vers la gauche.