今回はUnityで物理動作を行うRigidBody2Dの「BodyType」の違いを確認していきます。
はじめに
まずは「2DObject」→「Sprites」→「Circle」を追加します。

「Add Component」から「Rigidbody2D」を追加します。

RigidBodyのBodyType
RigidBody2Dの1番上にあるBodyTypeの項目には、「Dynamic(動的)」、「Kinematic」、「Static(静的)」の3種類があります。

ボディタイプを変更すると、設定できる項目が変わります。
具体的な違い
実際にどう違うのかを具体的に見ていきます。
Dynamic(動的)
初期値のDynamicの状態で動かしてみると、下に落ちていきます。

Dynamic(動的)は、質量、重力スケールが初期値で設定されているので、その影響で下に落ちています。Dynamicは、一般的なボディタイプなのでデフォルトでセットされます。設定項目(プロパティ)も多いため、3種類の中で一番パフォーマンスに高い負荷がかかります。
次に、スクリプトを追加して、ボールに力を加えてみます。まずは、下に落ちないように重力スケールを0にします。

Movingと言う名前でスクリプトを追加します。

スクリプトの中身は下記に変更します。
using UnityEngine; public class Moving : MonoBehaviour { private Vector2 _move; private float _force = 3.0f; private Rigidbody2D _rb; void Start() { _rb = GetComponent<Rigidbody2D>(); } void Update() { _move = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); _rb.AddForce(_move * _force); } }
実行してキー入力すると下記のような感じにボールに力が加わります。

Kinematic
ボディタイプをキネマティックに変更するとプロパティが減り、重力と力の影響をうけなくなります。

この場合、物体を動かす方法としては「速度(力の影響受けない)」か「再配置」です。下記が速度で動かす場合のスクリプト例です。
using UnityEngine; public class Moving : MonoBehaviour { private Rigidbody2D _rb; void Start() { _rb = GetComponent<Rigidbody2D>(); _rb.velocity = new Vector2(1, 0); } }
質量に関係するプロパティがないため、無限に大きな質量があるかのように動作します。プロパティが減るため、dynamicよりもシステムリソースに負荷をかけないです。
Static(静的)
全く動かないのがStaticです。

ためしに、動かそうとするとエラーが出ます。

特徴としては、全く動かない、もっともリソースに負荷がかからない。と言った感じです。