Unity5学習の際の覚え書き。

Rigidbodyとは

オブジェクトに物理的な力を受ける「形」を与える。

Rigidbodyの追加方法

  • ゲームオブジェクトを選択し、「Add Component -> Physics -> Rigidbody」
  • ゲームオブジェクトを選択し、「Component -> Physics -> Rigidbody」

Rigidbodyの設定

Mass
ゲームオブジェクトの質量。

Drag
ゲームオブジェクトが移動するときの「空気抵抗」。「0」で空気抵抗無し、「Infinity」で空気抵抗が無限大となり動かなくなる。

Angular Drag
ゲームオブジェクトが回転するときの「空気抵抗」。

Use Gravity
ゲームオブジェクトに「重力」を適用するかどうかの設定。チェックすると重力が働き、落下するようになる。

Is Kinetic
物理挙動をさせない。チェックすると物理挙動をしなくなる。

Rigidbodyのメソッド

力を加える「AddForce」メソッド

<Rigidbody> .AddForce( <Vector3> );
<Rigidbody> .AddForce( x値, y値, z値 );

引数には、そのオブジェクトにかける力の向きを示すVector3インスタンスが入る。
例えば、new Vector3(1, 2, 3)でできたインスタンスをAddForceに設定すれば、x軸方向に1、y軸方向に2、z軸方向に3の力を加えることができ、これらの力を合わせた方向に力が加えられる。
Vector3を使わず、3つの値をそれぞれ引数に指定することも可能。

Sphereをキーボードで転がすスクリプト

public class rigidscript : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		// 手前から奥にかけてがz軸
		if (Input.GetKey (KeyCode.UpArrow)) {
			transform.GetComponent<Rigidbody>().AddForce (0, 0, 1);
		}
		if (Input.GetKey (KeyCode.DownArrow)) {
			transform.GetComponent<Rigidbody>().AddForce (0, 0, -1);
		}
		// 横方向がx軸
		if (Input.GetKey (KeyCode.RightArrow)) {
			transform.GetComponent<Rigidbody>().AddForce (1, 0, 0);
		}
		if (Input.GetKey (KeyCode.LeftArrow)) {
			transform.GetComponent<Rigidbody>().AddForce (-1, 0, 0);
		}
	}
}

その他のメソッド

AddRelativeForce相対座標で力を加える
AddTorque回転を加える
AddRelativeTorque回転を加える

オブジェクトの速度

「速度」の情報を取り出し、それを再設定すれば、「急にスピードアップする」とか「いきなり遅くなる」といった操作ができるようになる。

オブジェクトの速度のプロパティ

<GameObject>.GetComponent<Rigidbody>().velocity
値はVector3インスタンス。
値を変更すると、オブジェクト自身が持っている速度を変えることができる。

オブジェクトの回転速度のプロパティ

<GameObject>.GetComponent<Rigidbody>().angularVelocity
値はVector3インスタンス。

ぶつかったら加速するスクリプト

public class myscript : MonoBehaviour {

	void Start () {
	}

	void Update () {
		GameObject cube = GameObject.Find ("Cube");
		cube.transform.Rotate(1f, -1f, -1f);
	}

	void OnTriggerEnter(Collider collider){
		if (collider.gameObject.tag == "Player") {
			GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
			GetComponent<Rigidbody>().velocity = Vector3.zero;
		}
	}

	void OnTriggerExit(Collider collider){
		if (collider.gameObject.tag == "Player") {
			Vector3 v = GetComponent<Rigidbody>().velocity;
			Vector3 v3 = new Vector3 (10, 10, 10);
			v += v3;
			GetComponent<Rigidbody>().velocity = v;

			Vector3 v2 = GetComponent<Rigidbody>().angularVelocity;
			v2.x += 2;
			v2.y += 2;
			v2.z += 2;
			GetComponent<Rigidbody>().angularVelocity = v2;
		}
	}
}

コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

Menu

【メニュー編集】
Wiki記法ガイド

リンク

ゲームバー大阪心斎橋

ゲームバー大阪梅田

ゲームバー大阪心斎橋

ダーツ&ダイニングバー大阪梅田

メニュー

Unity


スマホ操作

Unity - GameObject

Unity - 3DCG

メンバーのみ編集できます