nomurabbitのブログ

nomurabbitのブログはITを中心にした技術ブログです。

nomurabbitのブログ

【Unity】プレイヤーをDualshock4で動かしてみた【3DCG】

この記事はUnity 2020.3.26f1を使ったゲーム制作について勉強した内容をまとめたものです。


こんにちは!らびです。今回はプレイヤーDualshock4で動かしてみます。

頑張って勉強していきましょう!


今回の目標


今回はUnityのゲーム内でプレイヤーDualshock4で操作してみます。


用意したサンプルはこちらです。


f:id:nomurabbit:20220316175734p:plain


前回作ったプロジェクトを利用するジョ。

Dualshock4のボタンのマッピング


Dualshock4のボタンをUnityからアクセスできる変数に割り当てます。Edit、Project Settings...を選択します。


f:id:nomurabbit:20220316175805p:plain


Input Managerにて、


f:id:nomurabbit:20220316175921p:plain


Sizeを1インクリメントしておきます。


f:id:nomurabbit:20220316180013p:plain


f:id:nomurabbit:20220316180203p:plain


すると、一番下にCancelが複製されていると思います。


f:id:nomurabbit:20220316180108p:plain


同じ要領でもう一つInputを追加して、下記のように設定します。


f:id:nomurabbit:20220316181543p:plain


8th axiosが十字キーの上下、7th axiosが十字キーの左右です。


これでDualshock4の入力をUnityで取得できるようになりました。


Unityで取得した入力はControllerで制御できます。

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

public class PlayerController : MonoBehaviour
{
	public float speed = 0.3f;

	// Start is called before the first frame update
	void Start()
	{
		
	}

	// Update is called once per frame
	void Update()
	{
		if (Input.GetAxis("Move01") > 0.2)
		{
			transform.position += transform.forward * speed * Time.deltaTime;
		}
		else if (Input.GetAxis("Move01") < -0.2)
		{
			transform.position -= transform.forward * speed * Time.deltaTime;
		}
		else
		{
			// no move
		}

		if (Input.GetAxis("Move02") > 0.2)
		{
			transform.position += transform.right * speed * Time.deltaTime;
		}
		else if (Input.GetAxis("Move02") < -0.2)
		{
			transform.position -= transform.right * speed * Time.deltaTime;
		}
		else
		{
			// no move
		}


		if (Input.GetKey("up") || Input.GetKey("w"))
		{
			transform.position += transform.forward * speed * Time.deltaTime;
		}
		if (Input.GetKey("down") || Input.GetKey("s"))
		{
			transform.position -= transform.forward * speed * Time.deltaTime;
		}
		if (Input.GetKey("right") || Input.GetKey("d"))
		{
			transform.position += transform.right * speed * Time.deltaTime;
		}
		if (Input.GetKey("left") || Input.GetKey("a"))
		{
			transform.position -= transform.right * speed * Time.deltaTime;
		}
	}
}

まとめ


以上、プレイヤーDualshock4で動かす方法について勉強した内容のまとめでした。


Unityでできることを増やして、いろんなゲームを作成したいですね。


次回もぜひご覧ください。では!