From Test-Scratch-Wiki
In this tutorial we will explain how to make a sprite always be where the mouse is, follow the mouse indefinitely, if a button is pressed, if the mouse is too close to the sprite, or have the sprite follow at a distance.
Tip: | These scripts can make sprites follow other sprites, not just the mouse. |
Always Going to the Mouse
This script makes a sprite always be at the location of the mouse:
when green flag clicked forever go to [mouse-pointer v]
The Draggable Sprite Feature can also be used, but this requires the user to click.
Following the Mouse Indefinitely
This script will make the sprite follow the mouse no matter what the circumstance:
when green flag clicked forever point towards [mouse-pointer v] move (10) steps
Alternatively, you can use the following script:
when green flag clicked forever glide (0.1) secs to x: (mouse x) y: (mouse y)
This gives the object following the mouse a bit more of a velocity.
Following the Mouse if a Boolean is True
This script makes a sprite follow the mouse if the left-mouse button is pressed. Any Boolean blocks can be used in place of the Mouse Down?.
when green flag clicked forever if <mouse down?> then point towards [mouse-pointer v] move (10) steps
Following the Mouse if a Sprite Comes Close Enough
This script will make the sprite follow the mouse, but only if the mouse-pointer comes within a certain distance of the sprite.
when green flag clicked forever if <(distance to [mouse-pointer v]) < [100]> then point towards [mouse-pointer v] move (10) steps
Following the Mouse at a Distance
This script will make the Sprite follow the mouse indefinitely, but will never come to touch the mouse. One thing to notice about the script is that there is that there is a cushion zone. If the Distance is between 50 and 70 then nothing will happen. This is designed so that the sprite will not jump or bounce erratically.
when green flag clicked forever point towards [mouse-pointer v] if <(distance to [mouse-pointer v]) < [50]> then move (-10) steps end if <(distance to [mouse-pointer v]) > [70]> then move (10) steps end end
Following the Mouse Quicker as the Mouse Moves Away
This script will make the Sprite follow the mouse indefinitely. As the mouse gets farther away from the sprite, the sprite will speed up until it gets closer again, slowing down.
when green flag clicked forever point towards [mouse-pointer v] move ((distance to [mouse-pointer v]) / (12)) steps end
Note: the number 12 can be increased to make the sprite follow more slowly, or decreased to make the sprite faster.