Teachers open the door but You must enter by yourself.

Open Media Lab.
オープンメディアラボ

キー入力によるオブジェクト操作
Manipulate Object with Key Input

【事前学習】前回学んだ基本操作を再確認しておきましょう。

打ち返しパッドを追加してボールを操作できるようにしてみましょう。本ページの操作をただ読んだままに実践するだけでなく、それぞれの操作の意味を噛みしめながら進めてください。

操作手順
Procedure

打ち返しパッド用オブジェクトの追加

Hierarchy/+ボタン/3D Object/Cubeで立方体を追加し、名前をPadなどに変更し、青色など適当な色を付けます。

Cubeを選択した状態でInspectorのPositionを(0, 0, -3.5)、Scaleを(1, 1, 0.25)に変更します。


//Pad.csに追加
void Start()
{
	name="Pad";
	transform.position=new Vector3(0,0,-3.5f);
	transform.localScale=new Vector3(1,1,0.25f);
	GetComponent<Renderer>().material.color=new Color(0,0,1,1);
}

打ち返しパッドの動きの追加

Window/PackageManagerで+ボタンの横のプルダウンメニューでUnity Registryに切り替えるとInput Systemが表示されるようになるので、これをInstallする(Installボタンを押す)。BackEndを起動するかと問われるのでyesのボタンを押す。少し時間がかかるがUnityが再起動する。

PadにAddComponentでInput/Player Inputを追加し、追加された Player Input コンポーネント内で Create Actions ボタンを押して inputactions ファイルを作成します。

PadのInspectorで一番下のAddComponentボタンを押し、New Scripを選択して(スクロールしないと表示されていない時があります)新しいスクリプトファイルを生成します。名前はたとえばPadに変更します。

C#Scriptのアイコンをダブルクリックしてエディタで開き、以下のようにコードを追加します。


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class Pad : MonoBehaviour
{
	public float speed = 0.1f;
	float dx;

	void Start()
	{

	}

	void OnMove(InputValue input)
	{
		var vector2d = input.Get<Vector2>();
		dx = vector2d.x;
	}

	void FixedUpdate()
	{
		var position = transform.position;
		if (dx > 0 && position.x < 2){
			//右方向キーが押された かつ ボールが枠内にある
			position.x += speed; //パッドを右にずらす
		}else if (dx < 0 && position.x > -2){
			//左方向キーが押された かつ ボールが枠内にある
			position.x -= speed; //パッドを左にずらす
		}
		transform.position = position;
	}

	void Update()
	{
	}
}

左右方向キーでパッドが左右に動かせることを確認してください。

スクリプトの処理の対象は基本的にはそのスクリプトがアタッチされているオブジェクトに対して実行されます。この場合はパッドになります。FixedUpdate関数内でまずパッドの位置transform.positionをローカル変数positionにコピーすることにより取り出します。次にpositionの値をキー入力に合わせて変更し、最後にtransform.positionに再度コピーすることによりパッドの位置の変更を実現します。

コード内ではキーのオンオフを直接取得するのではなく、OnMove関数内で得られた左右方向の移動量 dx を用いています。このようにUnityではActionに応じて得られる入力を用いて記述し、例えば今回の水平方向移動に対して、実際のデバイスにはキーやゲームパッドの左右キーなど色々入力デバイスをアタッチできるように設計されています。


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class Pad : MonoBehaviour
{
	public float speed = 0.1f;

	void Awake(){ //Start()よりも前に実行される
		var inputActionAsset
			= ScriptableObject.CreateInstance<InputActionAsset>();
		var map = inputActionAsset.AddActionMap("Player");
		var action = map.AddAction(
			"Move",
			InputActionType.Value
		);
		action.AddCompositeBinding("2DVector")
			.With("Up", "<Keyboard>/upArrow")
			.With("Down", "<Keyboard>/downArrow")
			.With("Left", "<Keyboard>/leftArrow")
			.With("Right", "<Keyboard>/rightArrow");
		action.performed += OnMove;
		action.Enable();
	}

	void Start(){
		name="Pad";
		transform.position=new Vector3(0,0,-3.5f);
		transform.localScale=new Vector3(1,1,0.25f);
		GetComponent<Renderer>().material.color=new Color(0,0,1,1);
	}

	float dx;

	void OnMove(InputAction.CallbackContext c){
		var vector2d = c.ReadValue<Vector2>();
		dx = vector2d.x;
	}

	void FixedUpdate(){
		var position = transform.position;
		if (dx > 0 && position.x < 2){
				position.x += speed;
		}else if (dx < 0 && position.x > -2){
			position.x -= speed;
		}
		transform.position = position;
	}
}


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pad : MonoBehaviour
{
	public float speed = 0.1f;

	void Start(){
		
	}

	void Update(){
		Vector3 position = transform.position;
		if(Input.GetAxis("Horizontal") > 0 && position.x < 2){
			//右方向キーが押されている かつ 枠内にあるなら右に少しずらす
			position.x += speed; 
		}else if(Input.GetAxis("Horizontal") < 0 && position.x > -2){
			//左方向キーが押されている かつ 枠内にあるなら左に少しずらす
			position.x -= speed;
		}
		transform.position = position;
	}
}

This site is powered by Powered by MathJax