スマホタッチ
キーボード応用
スマホの指のタッチも追加したもの
押す.A 入力.A 離す.Aのように使える
タッチ1、 タッチ2、 タッチ3、 タッチ4、 タッチ5
スマホタッチのエリア割り当てがある
プログラムではタッチ1のエリアが上画面3分の1 タッチ2が下画面の左半分
タッチ3が下画面の右半分になっている
上画面を長押ししている時もう1つの指で上画面を押してもタッチ1が既に使われているので反応しない。
Vector2 pos = タッチ位置.タッチ1;でタッチ1の指の位置が分かる
using System.Collections.Generic;
using UnityEngine;
public class スマホタッチ : MonoBehaviour
{
void Start()
{入力管理.初期化();}
void Update()
{ 入力管理.更新(); }
}
public static class 指押す
{
public static bool タッチ1, タッチ2, タッチ3, タッチ4, タッチ5;
}
public static class 指入力
{
public static bool タッチ1, タッチ2, タッチ3, タッチ4, タッチ5;
}
public static class 指離す
{
public static bool タッチ1, タッチ2, タッチ3, タッチ4, タッチ5;
}
public static class タッチ位置
{
public static Vector2 タッチ1, タッチ2, タッチ3, タッチ4, タッチ5;
}
public static class 入力管理
{
const int 最大タッチ数 = 5;
static int[] エリア担当指 = new int[最大タッチ数 + 1];
static int エリアからタッチ番号(Vector2 pos)
{
float w = Screen.width;
float h = Screen.height;
if (pos.y > h * 0.66f)
return 3;
if (pos.x < w * 0.5f)
return 1;
return 2;
}
public static void 初期化()
{
for (int i = 1; i <= 最大タッチ数; i++)
{
string 名 = $"タッチ{i}";
設定(typeof(指押す), 名, false);
設定(typeof(指入力), 名, false);
設定(typeof(指離す), 名, false);
設定位置(typeof(タッチ位置),名, Vector2.zero);
エリア担当指[i] = -1;
}
}
public static void 更新()
{
for (int i = 1; i <= 最大タッチ数; i++)
{
設定(typeof(指押す), $"タッチ{i}", false);
設定(typeof(指離す), $"タッチ{i}", false);
設定(typeof(指入力), $"タッチ{i}", false);
}
int count = Input.touchCount;
for (int i = 0; i < count; i++)
{
Touch t = Input.GetTouch(i);
int 指ID = t.fingerId;
int 番号 = エリアからタッチ番号(t.position);
string 名 = $"タッチ{番号}";
設定位置(typeof(タッチ位置),名, t.position);
if (エリア担当指[番号] != -1 && エリア担当指[番号] != 指ID)
{
continue;
}
if (エリア担当指[番号] == -1)
{
エリア担当指[番号] = 指ID;
}
if (t.phase == TouchPhase.Began)
設定(typeof(指押す), 名, true);
if (t.phase == TouchPhase.Began||t.phase == TouchPhase.Moved || t.phase == TouchPhase.Stationary)
設定(typeof(指入力), 名, true);
if (t.phase == TouchPhase.Ended || t.phase == TouchPhase.Canceled)
{ 設定(typeof(指離す), 名, true); エリア担当指[番号] = -1; }
}
}
static void 設定(System.Type クラス, string 名, bool 値)
{
クラス.GetField(名).SetValue(null, 値);
}
static void 設定位置(System.Type クラス,string 名, Vector2 値)
{
クラス.GetField(名).SetValue(null, 値);
}
}
説明
if (エリア担当指[番号] != -1 && エリア担当指[番号] != 指ID)
「担当が自分なら処理する、他人なら無視する」
これを実現するために
!= -1 だけでは不十分で、
!= 指ID のチェックが必須。

