復習:入力の切り替え
CoddyのUnityジャーニー「本格的なゲームを作る」セクションの一部。レッスン 48/60。
この章では、Input Systemを使ってキーボード、マウス、プロジェクトのアクションを読み取りました。泡の杖では今も古いInputクラスを使っています。呼び出しごとに移行しましょう。
チャレンジ
中級バブルの杖をInput Systemに移行しましょう。ここでは古いInputクラスを使うとエラーになります。
using UnityEngine.InputSystem;を追加し、InputAction型のフィールドmoveActionとjumpActionを追加して、Start()でInputSystem.actions.FindActionを使って設定します。moveAction.ReadValue<Vector2>()で移動します。yの値はz方向に使います。- Jumpの判定を
WasPressedThisFrame()、IsPressed()、WasReleasedThisFrame()に置き換え、クリック判定をMouse.current.leftButton.wasPressedThisFrameに置き換えます。
「プレイ」を押して、バブルを膨らませてから割りましょう。その後、「確認」を押します。
自分で試してみよう
using UnityEngine;
public class Wand : MonoBehaviour
{
public float speed = 4f;
public float growRate = 1f;
public float maxSize = 1.5f;
public GameObject bubblePrefab;
private Transform bubble;
void Update()
{
Vector3 move = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
transform.position += move.normalized * speed * Time.deltaTime;
if (Input.GetButtonDown("Jump"))
{
bubble = Instantiate(bubblePrefab, transform.position + Vector3.up * 1.5f, Quaternion.identity).transform;
}
if (Input.GetButton("Jump") && bubble != null)
{
float size = Mathf.Min(bubble.localScale.x + growRate * Time.deltaTime, maxSize);
bubble.localScale = Vector3.one * size;
}
if (Input.GetButtonUp("Jump") && bubble != null)
{
Debug.Log("Bubble: " + bubble.localScale.x.ToString("F1"));
bubble = null;
}
if (Input.GetMouseButtonDown(0))
{
GameObject[] bubbles = GameObject.FindGameObjectsWithTag("Bubble");
foreach (GameObject b in bubbles) Destroy(b);
Debug.Log("Popped " + bubbles.Length);
}
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
本格的なゲームを作るのすべてのレッスン
自分で練習してみよう: Unityプレイグラウンド