Exercise 8: Move the sprite using the mouse
This exercise is based on the previous one - the
main difference is that the car is controlled by the mouse rather
than by the arrow keys. This actually gives us simpler code: only
one script! You can use a copy of the project you already
saved in exercise 7 but don't lose that project. The simplest thing
to do is open project 7 and then use 'Save As' to save the modified
project with a new name such as 'car race with mouse'. Remember that
'Save As' is used when you you want to save a new version
(new name or new location) of an existing file without
changing the existing file.
Study the script carefully. What changes can you
see? Probably the first thing you notice is the
'set size to 35%'
block. Including a block like this is an alterative to using the
'shrink sprite' and 'grow sprite' tools. We also note that a 'forever
if' loop replaces the 'forever' loop of
the previous project. This change was needed because there is
otherwise a problem when the car is not moving - it tends to
'judder'. Try replacing the 'forever if' loop with a 'forever' loop
and you will see the problem. The 'forever if' loop solves the
problem by doing nothing when the mouse pointer is very close to the
centre of the car.
Also new in this script if an 'if.... else'
loop. If the loop detects that the black of the car's
perimeter is touching the green of the grass then the speed of he
car is set to 1 (very slow). Otherwise ('else') the car is
given a speed that depends on how far away the mouse-pointer is
located. I divided that distance by 12 to give a speed behaviour
that seemed right to me - try changing the 12 to get the behaviour you
prefer. You can also try changing the size of the car. Play with the
script and try extending the program in original ways.
As mentioned earlier, be careful not to replace the
Project 7 file with the newly-modified version, use 'Save As' so
that you can give the modified file a new name such as 'car race
with mouse'.