LoginSignup
0
0

More than 1 year has passed since last update.

Unityで当たり判定を追加する

Last updated at Posted at 2022-04-18

2022.4.18 5日目 今日はUnityで、読み込んだExcelデータを表示した後、そのデータを条件によってソートしてみます。

準備

以前にやったExcelデータを表示して以下GIFのような動作を実装しておきます。

ダウンロード.gif

ポップアップで表示しているcellは以下のようになっております。
「ID Name Level」の順で表示しています。
bandicam 2022-04-18 12-18-17-020.jpg

データはExcelで管理しております。
bandicam 2022-04-18 12-22-07-222.jpg

今回は、IDかLevelでソートできるようにしていきます。

ソートポップアップの準備

以下のように、ソートのポップアップを表示したら、ポップアップの外側をクリックすると非アクティブになるようにします。

以下のサイトを参考にしました。(感謝)
https://unity-senpai.hatenablog.com/entry/2019/03/27/012403

当たり判定をPopupにつけました。
BoxCollider2Dを付けて、IsTriggerにチェックを付けました。
bandicam 2022-04-18 17-37-52-744.jpg
bandicam 2022-04-18 17-38-15-506.jpg

以下のようなスクリプトを作成し、Popupにアタッチします。

SortPopup.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class SortPopup: MonoBehaviour {

    [SerializeField] public GameObject sortPopup;

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

    }

    // Update is called once per frame
    void Update() {
        //ソートポップアップが無かったらreturn
        if( sortPopup.activeSelf == false ) {
            return;
        }

        //マウスでクリックしたら
        if( Input.GetMouseButtonDown( 0 ) ) {

            //Rayを飛ばして
            Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );

            //Rayの先に当たり判定のあるオブジェクトがあるかどうか
            RaycastHit2D rayHit2D = Physics2D.Raycast( ( Vector2 ) ray.origin, ( Vector2 ) ray.direction );
            
            //なかったらソートポップアップを消す
            if( !rayHit2D ) {
                sortPopup.SetActive( false );
            }
        }

    }
}

これでソートのポップアップを表示したら、ポップアップの外側をクリックすると非アクティブになるようになりました。

ソートを実装する(仮)

public void OnClickLevelSortButton() {
        
        for( int i = 0; i < cellNum; i++ ) {
            GameObject temp = null;
            if( _instance[ i ].GetComponent<Cell>().getCellLevel() > _instance[ i + 1 ].GetComponent<Cell>().getCellLevel() ) {
                temp = _instance[ i ];
                _instance[ i ] = _instance[ i + 1 ];
                _instance[ i + 1 ] = temp;
            }
        }
}

こんな感じで書いてみましたが、別の場所でエラーが出てしまったので、明日はそこを修正して、動作を確認します。

今日は終わりです。

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