From Test-Scratch-Wiki

Translate: - English - 中文 
SandCastleIcon.png 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.

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

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 Note: Do not put this script into an object intended to be static (non-moving).
當 @greenflag 被點擊
定位到 x: (0) y: (0)
變數 [y speed v] 設為 (0)
變數 [x speed v] 設為 (0)
重複無限次 
  如果 <([abs v] 數值 (([x 座標 v] \( [角色1 v] \)) - ([x 座標 v] \( [角色2 v] \)))) < [50]> 那麼 
    如果 <([x 座標 v] \( [角色2 v] \)) > (x座標)> 那麼 
      變數 [x speed v] 改變 (-0.1)
    end
    如果 <([x 座標 v] \( [角色2 v] \)) < (x座標)> 那麼 
      變數 [x speed v] 改變 (0.1)
    end
  end
  如果 <([abs v] 數值 (([y 座標 v] \( [角色1 v] \)) - ([y 座標 v] \( [角色2 v] \)))) < [50]> 那麼 
    如果 <([y 座標 v] \( [角色2 v] \)) > (y 座標)> 那麼 
      變數 [y speed v] 改變 (-0.1)
    end
    如果 <([y 座標 v] \( [角色2 v] \)) < (y 座標)> 那麼 
      變數 [y speed v] 改變 (0.1)
    end
  end
end

當 @greenflag 被點擊
重複無限次 
  碰到邊緣就反彈
  x 改變 (x speed)
  y 改變 (y speed)
  變數 [x speed v] 設為 ((0.98) * (x speed))
  變數 [y speed v] 設為 ((0.98) * (y speed))
end

An example can be seen here.

Direct Movement Method

The Direct Movement Method uses the 程式 below to move and rotate based on its position. This method is basic, but very effective in doing its job.


Note Note: This script can only be used in one 角色 at a time unlike the velocity method.
當 @greenflag 被點擊
定位到 x: (0) y: (-1)
重複無限次 
  如果 <(與 [角色2 v] 的間距) < [50]> 那麼 
    面朝 [角色2 v] 向
    面朝 ((方向) - (4)) 度
    移動 (10) 點
    碰到邊緣就反彈
  end
end

An example can be seen here.

参见