From Test-Scratch-Wiki

Translate: - English - 中文 

In Object Attraction two or more objects are attracted to each other; or are pulling on each other. This can also be referred to as gravity.

Warning Tip: Please remember to adjust the scripts shown in this tutorial as necessary to best fit your 专案.

Elliptical Orbit Method

One way to make one object attracted to another object is to make a sprite "Orbit" around the other object. This method is always 100% accurate and will automatically move when the object that it is being rotated about moves. Here is a script that creates an elliptical orbit:

當 @greenflag 被點擊
變數 [distance v] 設為 [75]
變數 [rotation v] 設為 [0]
重複無限次 
  重複 (360) 次 
    x 設為 ((([sin v] 數值 (rotation)) * (distance)) + ([x 座標 v]\([角色2 v]\)))
    y 設為 ((([cos v] 數值 (rotation)) * (distance)) + ([y 座標 v]\([角色2 v]\)))
    x 改變 ((([cos v] 數值 (rotation)) * (distance)) * (1))
    y 改變 ((([cos v] 數值 (rotation)) * (distance)) * (1))
    變數 [rotation v] 改變 (1)
  end
end

Remember that this script goes in the object that is being rotated.

One example of the elliptical orbit method can be found here.

Velocity Method

Another method is to have a sprite change its velocity automatically based on its position. This method is very inaccurate however it can be very useful if your creating a game where you have to avoid multiple sprites. The Following scripts will be placed into the item that is "following" another sprite:

當 @greenflag 被點擊
變數 [y speed v] 設為 [0]
變數 [x speed v] 設為 [0]
重複無限次 
  如果 <([x 座標 v]\([角色2 v]\)) < (x 座標)> 那麼 
    變數 [x speed v] 改變 (-0.1)
  end
  如果 <([x 座標 v]\([角色2 v]\)) > (x 座標)> 那麼 
    變數 [x speed v] 改變 (0.1)
  end
  如果 <([y 座標 v]\([角色2 v]\)) < (y 座標)> 那麼 
    變數 [y speed v] 改變 (-0.1)
  end
  如果 <([y 座標 v]\([角色2 v]\)) > (y 座標)> 那麼 
    變數 [y speed v] 改變 (0.1)
  end
end

當 @greenflag 被點擊
重複無限次 
  定位到 x: ((x 座標) + (x speed)) y: ((y 座標) + (y speed))
end

One example of the velocity method can be seen here.

Trigonometric Method

Main article: Simulating Gravity


Direct Movement Method

This method although far more basic than the previous methods, can be very useful in certain situations. This method is very accurate and will move automatically with the sprite. Here is an example script that would be place in the sprite that is "following" the other sprite:

當 @greenflag 被點擊
重複無限次 
  面朝 [角色2 v] 向
  移動 (5) 點
end

One example of the direct movement method can be seen here.

Wall Method

This method sort of has a fast wall attraction.

當 @greenflag 被點擊
重複無限次 
  x 設為 ((10) * (滑鼠游標的 x))
  y 設為 ((10) + (滑鼠游標的 y))
end

参见