From Test-Scratch-Wiki
| This page has links to outside of the Scratch website or Wikipedia. Remember to stay safe when using the internet as we can't guarantee the safety of other sites. |
Object Repulsion is the act of repulsing or repelling an object. Listed below are two methods of replicating this effect in Scratch.
| Please remember to adjust the scripts shown in this tutorial as necessary to best fit your 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.
| Do not put this script into an object intended to be static (non-moving). |
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.
| 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]
point in direction ((direction) - (4))
move (10) steps
if on edge, bounce
An example can be seen here.