今回の内容
前回はプレイヤーの左右移動の処理を作成しました。
これまではゲームを開始したらプレイヤーが走り続ける実装としていましたが、
今回はマウスクリック or 画面をタップしている間だけ走り続ける実装に変更していきます。
なお、リリースされているランゲームを見ていると、
・常に走り続ける(最初だけタップしたら移動開始)
・タップしている間だけ走る
の2通りのパターンがあるように見えるので、実際にゲームを作成する際にはゲーム性に合わせて選択する形となります。
今回扱うタップしている間だけ走るパターンさえ押さえておけば、常に走り続けるパターンにも応用が効きます。
※初めての方はこちらから
⇒ 【第1回記事】導入とサンプルの紹介
PlayerScript と MovementBaseScript を変更
大きく変更点は2つあります。
1.タップしている間だけ移動する
2.移動している間だけ、プレイヤーのアニメ再生
先に2つ目の、プレイヤーのアニメに関する調整を行います。
PlayerScript を下記の通り変更してください。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
Animator animator;
public bool isRunning;
public float sensitivity = 1f;
const float LOAD_WIDTH = 6f;
const float MOVE_MAX = 2.5f;
Vector3 previousPos, currentPos;
void Start()
{
animator = GetComponent<Animator>();
}
void Update()
{
// スワイプによる移動処理
if (Input.GetMouseButtonDown(0))
{
previousPos = Input.mousePosition;
}
if (Input.GetMouseButton(0))
{
// スワイプによる移動距離を取得
currentPos = Input.mousePosition;
float diffDistance = (currentPos.x - previousPos.x) / Screen.width * LOAD_WIDTH;
diffDistance *= sensitivity;
// 次のローカルx座標を設定 ※道の外にでないように
float newX = Mathf.Clamp(transform.localPosition.x + diffDistance, -MOVE_MAX, MOVE_MAX);
transform.localPosition = new Vector3(newX, 0, 0);
// タップ位置を更新
previousPos = currentPos;
}
// isRunning = true; ※削除してください
animator.SetBool("IsRunning", isRunning);
}
}
9行目では isRunning を public に変更して、外部からアクセス可能にしています。
43行目は、説明の都合上コメントアウトとしていますが、1行丸ごと削除してください。
連載上でも、これ以降の PlayerScript を載せる箇所では削除します。
次に、MovementBaseScript を以下の通り変更します。
using PathCreation;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementBaseScript : MonoBehaviour
{
[SerializeField]
PathCreator pathCreator;
[SerializeField]
PlayerScript player;
float speed = 6f;
Vector3 endPos;
float moveDistance;
void Start()
{
endPos = pathCreator.path.GetPoint(pathCreator.path.NumPoints - 1);
}
void Update()
{
// タップ中は走る
if (Input.GetMouseButton(0))
{
moveDistance += speed * Time.deltaTime;
transform.position = pathCreator.path.GetPointAtDistance(moveDistance, EndOfPathInstruction.Stop);
transform.rotation = pathCreator.path.GetRotationAtDistance(moveDistance, EndOfPathInstruction.Stop);
player.isRunning = true;
}
else if (Input.GetMouseButtonUp(0))
{
player.isRunning = false;
}
}
}
11,12行目は、プレイヤーのアニメの再生・停止を制御するために、プレイヤー(PlayerScript)への参照を取得します。
27行目からがタップ状態による処理の切り替えを行っている箇所です。
ここまで記述できたら、最後にエディタで調整を行います。
Hierarchyビューで MovementBaseオブジェクトを選択し、
MovementBaseScript の Player に、Playerオブジェクトをドラッグ&ドロップで設定します。

これで変更完了となります。
(公式リファレンス)
Input.GetMouseButton
Input.GetMouseButtonUp
動作確認
最後に動作確認をしましょう。
タップによって移動・停止の切り替えができていれば成功です。

おわりに
メインの走る機能の実装がさらに完成に近づきました。
次回は移動に関連するヘルプUIを実装します!
関連リンク ➡ 「初心者のための」Unityゲーム制作 目次
© Unity Technologies Japan/UCL