私的メモ。
#キー入力でゲームオブジェクトを相対的に移動したい時、つまり、上下キーで前後に移動し左右キーで左右に方向を変えたい時
transform.Translate()やtransform.Rotate()を使う。
###移動
《Transform》.Tanslate( X値 , Y値 , Z値 );
《Transform》.Tanslate( X値 , Y値 , Z値 , 《Space》);
《Transform》.Tanslate(《Vector3》);
###回転
《Transform》.Rotate( X値 , Y値 , Z値 );
《Transform》.Rotate( X値 , Y値 , Z値 , 《Space》);
《Transform》.Rotate(《Vector3》);
Vector3インスタンスとしてはtransform.upとtransform.rightも使える。
transform.up ゲームオブジェクトが1だけ前に進む方向を示すVector3インスタンス。
transform.right ゲームオブジェクトが1だけ右に移動する方向を示すVector3インスタンス。
後や左にするには負の値をかければ良い。
###キー入力
Input.GetKey(キーの指定)で真偽値を得る。指定されたキーと入力が一致すればtrue、そうでなければfalseを返す。
キーの指定にはKeyCodeに用意されている値を使う。
http://docs.unity3d.com/ja/current/ScriptReference/KeyCode.html
#サンプル
using UnityEngine;
using System.Collections;
public class myscript : MonoBehaviour {
void Update () {
if (Input.GetKey (KeyCode.UpArrow))
this.transform.Translate (this.transform.up * 0.1f);
if (Input.GetKey (KeyCode.DownArrow))
this.transform.Translate (this.transform.up * -0.1f);
if (Input.GetKey (KeyCode.RightArrow))
this.transform.Rotate (new Vector3(0, 0, -1f));
if (Input.GetKey (KeyCode.LeftArrow))
this.transform.Rotate (new Vector3(0, 0, 1f));
}
}
普通にxyz指定してもよい。
using UnityEngine;
using System.Collections;
public class myscript : MonoBehaviour {
void Update () {
if (Input.GetKey (KeyCode.UpArrow))
this.transform.Translate (0, 0.1f, 0);
if (Input.GetKey (KeyCode.DownArrow))
this.transform.Translate (0, -0.1f, 0);
if (Input.GetKey (KeyCode.RightArrow))
this.transform.Rotate (0, 0, -1f);
if (Input.GetKey (KeyCode.LeftArrow))
this.transform.Rotate (0, 0, 1f);
}
}