Unityでゲームを作る1  主人公を動かす

1月 2, 2020

こんにちは。

これからunityでゲームを作っていきます。

完成ができるように頑張ります。

gameobjectの3d objectのcubeを選択します。

sacaleの値を変えて、大きくして、床を作ります。

次に、仮の主人公のオブジェクトを作ります。

gameobjectの3d objectのcapsuleを選択します。

床と主人公の両方が白だと、わかりにくいので床に色を付けます。

Assetsの何もない所で、右クリックして、createのmaterialを選択します。

そして、てきとうに色を付けて、床にドラッグアンドドロップをします。

次に主人公のオブジェクトを選択して、Add compornetのphysicsのrigidbodyを選択します。

次にrigidbodyのConstraintsのFreeze RotationのXとYとZにチェックを入れます。

Freeze Rotationは、回転させないようにするもので、チェックをいれた軸は回転しなくなります。

次に、主人公が動くように、コードを書きます。

Assetsの何もない所を右クリックして、createのC# Scriptを選択します。

作ったc# scriptをダブルクリックして、開きます。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
	//上のNewBehaviourScriptはスクリプトの名前
	public float walk = 0.05f; //歩く速さ
	public float run = 0.1f;  //走る速さ
	
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKey (KeyCode.W)) { //Wを押したら
			
			if (Input.GetKey (KeyCode.LeftShift)) { //シフトを押したら
				this.transform.Translate (0f, 0f, run); //前に走る
			} else {
				this.transform.Translate (0f, 0f, walk); //前に歩く
			}
		}
		if (Input.GetKey (KeyCode.S)) { //Sを押したら
			if (Input.GetKey (KeyCode.LeftShift)) {
				this.transform.Translate (0f, 0f, - run);
			} else {
				this.transform.Translate (0f, 0f, - walk);
			}
		}
		if (Input.GetKey (KeyCode.A)) {
			if (Input.GetKey (KeyCode.LeftShift)) {
				this.transform.Translate (- run, 0f, 0f);
			} else {
				this.transform.Translate (- walk, 0f, 0f);
			}
		}
		if (Input.GetKey (KeyCode.D)) {
			if (Input.GetKey (KeyCode.LeftShift)) {
				this.transform.Translate (run, 0f, 0f);
			} else {
				this.transform.Translate (walk, 0f, 0f);
			}
		}
	}
}

作ったスクリプトを主人公のオブジェクトに入れます。

これで、上の再生ボタンを押します。

うまくできたら、

Wを押したら前に、Sを押したら後ろに、Aを押したら左に、Dを押したら右に歩きます。

シフトを押しながらWASDを押すと走ります。