Object Repulsion is the act of repulsing or repelling an object. Listed below are two methods of replicating this effect in Scratch.
Tip: | Please remember to adjust the scripts shown in this tutorial as necessary to best fit a project. |
Velocity Method
The Velocity Method uses the following scripts to automatically make objects change their X and Y Velocity based upon their position. This script can go into any object that is being repelled. This method is more advanced than the next method, however this method is better in most situations.
Note: | Adding this will make the sprite move. |
when green flag clicked go to x: (0) y: (0) set [y speed v] to (0) set [x speed v] to (0) forever if <([abs v] of (([x position v] of (Sprite1 v)) - ([x position v] of (Sprite2 v)))) < [50]> then if <([x position v] of (Sprite 2 v)) > (x position)> then change [x speed v] by (-0.1) end if <([x position v] of (Sprite 2 v)) < (x position)> then change [x speed v] by (0.1) end end if <([abs v] of (([y position v] of (Sprite1 v)) - ([y position v] of (Sprite2 v)))) < [50]> then if <([y position v] of (Sprite 2 v)) > (y position)> then change [y speed v] by (-0.1) end if <([y position v] of (Sprite 2 v)) < (y position)> then change [y speed v] by (0.1) end end end when green flag clicked forever if on edge, bounce change x by (x speed) change y by (y speed) set [x speed v] to ((0.98) * (x speed)) set [y speed v] to ((0.98) * (y speed)) end
An example can be seen here.
Direct Movement Method
The Direct Movement Method uses the scripts below to move and rotate based on its position. This method is basic, but very effective in doing its job.
Note: | This script can only be used in one sprite at a time unlike the velocity method. |
when gf clicked go to x: (0) y: (-1) forever if <(distance to (Sprite2 v)) < [50]> then point towards (Sprite2 v) move (-10) steps if on edge, bounce
An example can be seen here.