0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unity+NGUIで仮想的にタッチ処理を呼ぶ話

Posted at

概要

諸般の都合でNGUIを使ってるプロジェクトでプログラムから座標を指定してタップ処理をコールする処理を作りました
・ゲーム内にカーソルを用意したい場合
・UIの自動テストをしたい場合
で利用できるかもしれません

まあ今更NGUI使う人はいないですよね
uGUIも似たような実装になってるの?機会があればコード読みます

検証環境

Unity: 2018.4.26f1
NGUI: 2019.3.0

実装

UICamera.csに以下を追記します

public void VirtualProcessTouch(Vector2 pos, bool pressed, bool unpressed)
{
    currentTouchID = 1;
    currentTouch = GetTouch(currentTouchID, true);
    currentTouch.touchBegan = pressed;
    if (pressed)
    {
        currentTouch.pressTime = RealTime.time;
        activeTouches.Add(currentTouch);
    }
    currentTouch.delta = pos - currentTouch.pos;
    currentTouch.pos = pos;
    currentKey = KeyCode.None;
    currentTouch.clickTime = RealTime.time;

    Raycast(currentTouch);

    ProcessTouch(pressed, unpressed);

    currentTouch.last = null;
    currentTouch = null;
}

あとは呼びたいところでVirtualProcessTouchをコールすればOKです
ツールチップやドラッグ処理をしたい場合はマイフレームコールする必要があるので注意。

解説

NGUIのUIへのタップ処理はUICameraで実装されています
Update関数からコード読むといいです
Update - ProcessEvents - ProcessTouches でタッチ処理が実装されてるのでコピぺしました
ちなみにRaycastは何もしてなくても全UICameraから毎フレーム飛ばしてます。

おまけ1

ProcessOthersにコントローラーを想定した処理がありますがUIKeyNavigationのための実装です。
これをボタンに設定しておくと十字キーでどのボタンに移動するか定義できるんですね。便利。

おまけ2

最初、自分でカメラからRaycastして要素を全取得してタップ処理をコールしようとしましたが
座標とdepthで前後関係がちゃんと取れなかったりScrollViewの子要素がとれてしまったりで無理でした
結果UICameraをいじるのが早かったというオチ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?