Dealing with collision events

Now that we have a collision mask, we can have our kart respond differently, depending on where it is driving. When on the road, the kart will increase throttle up to full speed. When hitting the sandbox it will be slowed down, and hitting the walls is even worse. The kart will bounce back and completely lose momentum.

Let's build these responses with a few scripts.

Engage thrusters

We will add a series of script instructions to the player1 sprite. We will assemble the instructions first, then place the script segment at the right spot in the existing script:

  1. Start with an if () then block.
  2. For the condition, we will check touching color ()?.
  3. Click on the color box and then on the sandy color of your collision mask with the eyedropper icon.
  4. Inside the if () then block, place a set <speed1> to () block.

When the kart drives through sand, we will slow it down. We do this by multiplying its current speed with a number smaller than 1 using these following steps:

  1. Place a () * () operator block in the vacant slot.
  2. Fill the left slot of the operator with the speed1 variable.
  3. Type in 0.8 in the right slot of the operator.
  4. To add the instructions for hitting the borders, copy the entire if () then statement and attach it to the original.
  5. Change the color to check for the green color that you used on the collision mask.

When hitting the border, the kart should bounce back. We do this by multiplying the speed with a negative number:

  1. Change 0.8 to -0.6.
  2. Grab the entire script and drag it to the existing when <green flag> clicked script. Place it between the if () then statement that checks for maximum speed and the move instruction.

This is all that you need to do for the bouncing-off-walls effect.

Engage thrusters

Objective complete – mini debriefing

Test the script and see how the kart responds to hitting the sandbox or the walls. It will no longer be possible to drive carefree across the stage. If you leave the road, the kart will come to a grinding halt giving your opponent an advantage.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.66.94