From Test-Scratch-Wiki

A sprite following the mouse

In this tutorial we will explain how to make a sprite always be where the 滑鼠 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.

Warning Tip: These 程式s can make sprites follow other 角色s, not just the mouse.

Always Going to the Mouse

This script makes a sprite always be at the location of the mouse:

當 @greenflag 被點擊
重複無限次 
  定位到 [滑鼠游標 v] 位置
end

The 角色可拖曳功能 can also be used, but this requires the user to click.

Following the Mouse Indefinitely

This script will make the 角色 follow the mouse no matter what the circumstance:

當 @greenflag 被點擊
重複無限次 
  面朝 [滑鼠游標 v] 向
  移動 (10) 點
end


Alternatively, you can use the following script:

 
當 @greenflag 被點擊
重複無限次 
  滑行 (0.1) 秒到 x: (滑鼠游標的 x) y: (滑鼠游標的 y)
end


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 菱形積木 can be used in place of the 滑鼠鍵被按下?.

當 @greenflag 被點擊
重複無限次 
  如果 <滑鼠鍵被按下?> 那麼 
    面朝 [滑鼠游標 v] 向
    移動 (10) 點
  end
end

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.

當 @greenflag 被點擊
重複無限次 
  如果 <(與 [鼠標 v] 的間距) < [100]> 那麼 
    面朝 [滑鼠游標 v] 向
    移動 (10) 點
  end
end

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.

當 @greenflag 被點擊
重複無限次 
  面朝 [滑鼠游標 v] 向
  如果 <(與 [鼠標 v] 的間距) < [50]> 那麼 
    移動 (-10) 點
  end
  如果 <(與 [鼠標 v] 的間距) > [70]> 那麼 
    移動 (10) 點
  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.

當 @greenflag 被點擊
重複無限次 
  面朝 [滑鼠游標 v] 向
  移動 ((與 [鼠標 v] 的間距) / (12)) 點
end

Note: the number 12 can be increased to make the sprite follow more slowly, or decreased to make the sprite faster.

Cookies help us deliver our services. By using our services, you agree to our use of cookies.