今回はjoystickを用いて、カメラがずっとプレイヤーに追従する機能の実装についてまとめてみました!
使用PC: MacBook Pro (13-inch, M1, 2020)
OSバージョン: 11.5.2
Unityバージョン:2020.3.20f1
実際にゲームをプレイすると
こんな感じになったら完成です!
目次
1.オブジェクトの準備
2.joystickの設定
3.スクリプトの作成
4.オブジェクトの代入
5.参考記事
オブジェクトの準備
①プレイヤー用のアセットをunityにインポートします。(今回はプレイヤーにunity asset storeのアセットを使いました。)
②地面とかは適当にplaneかcubeで作成してください。
プレイヤーにアニメーションはつけたりするのですが、その辺はちょっと今回は省かせていただきます。。。
joystickの設定
①joystickをasset storeからunityにインポートする
(※今回はFloating Joystickを使用します!Joystickの種類についてはこちらの記事がわかりやすく解説してくれているので参考にしてみてください!)
②HierarchyビューでCreate
→Canvas
を作成
③ProjectビューにインポートしておいたJoystick Packから、Floating JoystickをCanvasの子オブジェクトにドラッグ&ドロップ。
④canvasに内で位置や大きさを調整
スクリプトの作成
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
public FloatingJoystick idou;
public float speed;
Animator ani;
Quaternion qqq;
Quaternion rot;
// Start is called before the first frame update
void Start()
{
ani = this.gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
Move();
}
void Move()
{
float dx = idou.Horizontal;
float dy = idou.Vertical;
float rad = Mathf.Atan2(dx - 0, dy - 0);
float deg = rad * Mathf.Rad2Deg;
this.transform.rotation = Quaternion.Euler(0, rot.eulerAngles.y + deg, 0);
if (deg != 0)
{
ani.SetBool("Walk", true);
this.transform.position += this.transform.forward * speed * Time.deltaTime;
qqq = gameObject.transform.rotation;
}
else
{
ani.SetBool("Walk", false);
this.transform.rotation = Quaternion.Euler(0, qqq.eulerAngles.y, 0);
rot = gameObject.transform.rotation;
}
}
}
スクリプトの解説
コメントアウトに詳細を書きました。
①変数宣言
public FloatingJoystick idou; //入れたJoyStickの種類によって変えてください
public float speed; //Playerの移動速度。unity側で自由に設定してください。
Animator ani;
Quaternion qqq; //Playerが移動しているときの角度
Quaternion rot; //Playerが停止しているときの角度
②void Move関数の中身~その1~
float dx = idou.Horizontal; //joystickの水平方向の動き-1~1の値をとります
float dy = idou.Vertical; //joystickの垂直方向の動き-1~1の値をとります
float rad = Mathf.Atan2(dx - 0, dy - 0); // 原点(0,0)と点(dx,dy)の距離から角度をとってくれる便利な関数
float deg = rad * Mathf.Rad2Deg; //radianからdegreeに変換します
this.transform.rotation = Quaternion.Euler(0, rot.eulerAngles.y + deg, 0);
//Playerの向きを停止時に取得した角度に当てはめて代入します。今回はy軸方向が回転軸になります。
②void Move関数の中身~その2~
if (deg != 0) //joystickの原点と(dx,dy)の2点がなす角度が0ではないとき = joystickを動かしている時
{
ani.SetBool("Walk", true);
this.transform.position += this.transform.forward * speed * Time.deltaTime; //正面方向へプレイヤーを移動させ続ける
qqq = gameObject.transform.rotation; //動いている時の角度を取得する
}
else //joystickの原点と(dx,dy)の2点がなす角度が0の時 = joystickが止まっている時
{
ani.SetBool("Walk", false);
this.transform.rotation = Quaternion.Euler(0, qqq.eulerAngles.y, 0); //停止時のプレイヤーの動きの向きを設定
rot = gameObject.transform.rotation; //停止している時の角度を取得する
}
オブジェクトの代入
①PlayerになるオブジェクトにPlayerScript.cs
をドラッグ&ドロップで貼り付け
②PlayerScriptにjoystickを紐付けする。speedはいい感じになるように数値を入れてください。
③Main CameraをPlayerの子オブジェクトにして、いい感じの位置に調整する(今回使用したアセットではもともとカメラがついていましたが、動作上cameraを追加して使用しています)