Unityを学ぼう【第2回】
今回概要
- 物理法則適用
- 入力適用
物理法則適用:Rigidbody【リジッドボディ】
Rigidbodyの適用方法
1:[Hierarchy]に[Player]を選択します 2:[Inspector] -> [Add Component] -> [Physics] -> [Rigidbody] 3:Rigidbodyが追加されました
入力を適用:Script【スクリプト】
スクリプト作成
1:スクリプト用フォルダー作成 [ツールバー] -> [Assets] -> [Create] -> [Folder] 名前:Scripts 2:[Hierarchy]に[Player]を選択します 3:[Inspector] -> [Add Component] -> [New Script] 4:スクリプト名変更:PlayerController(図③) 5:使用言語を選択:CSharp(図④) 6:[Create and Add] *作成したスクリプトは[Assets]に保存されたので、スクリプトフォルダーに移動します
スクリプト編集*2
ソースコート
// PlayerController.cs using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { public float speed; // ① void FixedUpdate() // ② { float moveHorizontal = Input.GetAxis("Horizontal"); // ③ float moveVertical = Input.GetAxis("Vertical"); // ④ Vector3 movement = new Vector3(moveHorizontal,0.0f,moveVertical); // ⑤ rigidbody.AddForce(movement * speed * Time.deltaTime); // ⑥ } }
速度変数を宣言
public float speed; // ①
public で宣言した変数は [Inspector] に変更できます
更新関数
void FixedUpdate() // ②
Rigidbodyの更新は Update の代わりに FixedUpdate を使用します
入力値取得(Horizontal)
float moveHorizontal = Input.GetAxis("Horizontal"); // ③
キーボードの場合 [←] [→] の入力を取得できます
入力値取得(Vertical)
float moveVertical = Input.GetAxis("Vertical"); // ④
キーボードの場合 [↑] [↓] の入力を取得できます
移動方向変数
Vector3 movement = new Vector3(moveHorizontal,0.0f,moveVertical); // ⑤
Vector3は3D空間の[X,Y,Z]を表す変数です
今回は平面上に移動するので、Y軸を 0 に設定します
力を与える
rigidbody.AddForce(movement * speed * Time.deltaTime); // ⑥
AddForce は ターゲット(rigidbody)に力を与える関数です
与えた値を物理法則で反映されます
Time.deltaTime : フレームとフレームの間隔(秒)
実行&テスト
実行して、[↑] [↓] [←] [→]を入力してみようと~
あれ?動かんぞ
[Inspector]を見てみると Speed は 0 でした Speedを設定したら問題なく動きました
次回予告:カメラ移動を学ぼう