PC上の上下左右キーを使ってObjectを移動させてみましょう。Input.GetKeyを使うことで可能になります。Android, iPhoneアプリにする場合はキーが無いので別のものに代用する必要がありますが、まずPC上でのテストのためにこの工程は必要です。
Input.GetKey
ObjectとしてGameObjectのCapsuleを1つ作成し、TransformでX軸を90°RotationさせてObjectを横にしておきます。
このObjectを前後左右に動かしたいと思います。
以下のスクリプトを書いてCapsuleに入れます。
move.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class move2 : MonoBehaviour { void Start () { } void Update () { float dy = Input.GetAxis("Vertical"); float dx = Input.GetAxis("Horizontal"); if (Input.GetKey("up")) { transform.Translate(0, dy, 0); } if (Input.GetKey("down")) { transform.Translate(0, dy, 0); } if (Input.GetKey("left")) { transform.Translate(dx, 0, 0); } if (Input.GetKey("right")) { transform.Translate(dx, 0, 0); } } } |
Input.GetAxisは-1.0fから1.0fの値を返してきます。
Input.GetKeyはup,downなどのキーが押されたときに真となります。
もっとも、これは簡略化してこのようにもできます。
1 2 3 |
float dx = Input.GetAxis ("Horizontal"); float dy = Input.GetAxis ("Vertical"); transform.Translate (dx, dy, 0.0f); |
移動スピード、移動距離を調整したり、別条件を入れたい場合は最初の方法がいいかもしれません。
加速度センサーで移動させる
キー入力といってもスマホにはありません。スマホである特徴を活かしてスマホを傾けて加速度で移動させるのが面白いでしょう。以下のようなscriptでスマホの傾きを検出してObjectを移動できます。
1 2 3 4 |
var dir = Vector3.zero; dir.x = Input.acceleration.x; ... transform.Translate(dir); |
まとめるとこのようになります。
move_accelerator.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class move_accelerator : MonoBehaviour { private float speed = 10.0f; // Use this for initialization void Start() { } // Update is called once per frame void Update() { var dir = Vector3.zero; // ターゲット端末の縦横の表示に合わせてremapする dir.x = Input.acceleration.x; dir.z = Input.acceleration.y; // clamp acceleration vector to the unit sphere if (dir.sqrMagnitude > 1) dir.Normalize(); // Make it move 10 meters per second instead of 10 meters per frame... dir *= Time.deltaTime; // Move object transform.Translate(dir * speed); } } |
あとはCapsuleのスクリプトを入れ替えて「unity Remote 5」などで実機でテストするといいでしょう
ここまできてあれですが、ではキー入力はスマホをターゲットにしていればいらないのかというと、デバッグとして機能検証を行うときにUnity Editorでテストできます。if文で切り分けるなどしておくといいかもしれませんね。