上下(Y方向)、左右(X座標)、前後(Z方向)をキーボード操作で出来るようにしてみましょう。
【上下左右の動き】は十字キー、【前後の動き】はWキーとSキーで操作します。
関連記事:
【Unity C#】3D空間でプレーヤーを追いかけるオブジェクト
【Unity C#】簡単に十字キー操作できるスクリプト
【Unity C#】十字キーで1マスだけ移動する
KeyCodeの割り当て
Cubeオブジェクトを用意して、カラーを付けました。
カメラを少し近づけて、ゲームビューではこのように映っています。
CubeMove.csを作成して、Cubeに追加します。
CubeMove.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 CubeMove : MonoBehaviour { public float speed = 1.0f; void Update() { if (Input.GetKey (KeyCode.UpArrow)) { transform.position += transform.up * speed * Time.deltaTime; } if (Input.GetKey (KeyCode.DownArrow)) { transform.position -= transform.up * speed * Time.deltaTime; } if (Input.GetKey(KeyCode.RightArrow)) { transform.position += transform.right * speed * Time.deltaTime; } if (Input.GetKey (KeyCode.LeftArrow)) { transform.position -= transform.right * speed * Time.deltaTime; } if (Input.GetKey (KeyCode.W)) { transform.position += transform.forward * speed * Time.deltaTime; } if (Input.GetKey (KeyCode.S)) { transform.position -= transform.forward * speed * Time.deltaTime; } } } |
ゲームプレイしてみましょう。
【上下左右の動き】は十字キー、【前後の動き】はWキーとSキーで操作します。
関連記事:
【Unity C#】3D空間でプレーヤーを追いかけるオブジェクト
【Unity C#】簡単に十字キー操作できるスクリプト
【Unity C#】十字キーで1マスだけ移動する