In this video, you will make an obstacle move across the stage. In the finished game, itwill 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 samespot. To make it go to a random spot on the right side, add a “pick random” blockfrom the “operators” menu, and place it in the y value. Change the values to negative180 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 “repeatuntil” 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 thiscase, the obstacle should repeat moving to the left until it reaches the left edge ofthe stage. From the “motion” menu, drag out a “changex by” block, and insert it into the “repeat until” loop. Since the sprite needs to moveleft 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. Addan “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 isless than negative 240.” In other words, “repeat moving to the left until the spriteis 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 spoton 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, andmotion blocks.
In the next video, you’ll program this obstacle to copy itself forever, making more obstaclesto avoid.