栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > Unity3D

TouchScript For Unity (二)实时触摸射线检测

Unity3D 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

TouchScript For Unity (二)实时触摸射线检测

using System.Collections.Generic;
using TouchScript;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class PlayerHit : MonoBehaviour
{
    // 用于射线检测的的摄像头
    public Camera RayCamera;
    List list;
    private void OnEnable()
    {
        if (TouchManager.Instance != null)
            TouchManager.Instance.PointersUpdated += pointersUpdatedHandler;

        list = new List();
    }

    private void OnDisable()
    {
        if (TouchManager.Instance != null)
            TouchManager.Instance.PointersUpdated -= pointersUpdatedHandler;
    }


    void Start()
    {
        // 获取用于射线检测的的摄像头
        if (RayCamera == null)
            RayCamera = GameObject.FindGameObjectWithTag("RayCamera").GetComponent();
    }

    // 3D射线检测
    void RayHit3DFunction(Vector2 pos)
    {
        UnityEngine.Ray ray = RayCamera.ScreenPointToRay(pos);
        RaycastHit[] hits = Physics.RaycastAll(ray);
        if (hits.Length > 0)
        {
            foreach (var item in hits)
            {
                GameObject colObj = item.collider.gameObject;
                print(item.collider.gameObject.name);
                //if (colObj.CompareTag("3D") && colObj.activeSelf)
                //{

                //}
            }
        }
    }


    //2D UGUI 射线检测
    void RayHit2DFunction(Vector2 pos)
    {
        list = GraphicRaycaster(pos);
        foreach (var item in list)
        {
            GameObject colObj = item.gameObject;
            print(item.gameObject.name);
            //if (colObj.CompareTag("2D") && colObj.activeSelf)
            //{

            //}
        }

    }

    public EventSystem _mEventSystem;
    public GraphicRaycaster gra;
    private List GraphicRaycaster(Vector2 pos)
    {
        var mPointerEventData = new PointerEventData(_mEventSystem);
        mPointerEventData.position = pos;
        List results = new List();

        gra.Raycast(mPointerEventData, results);
        return results;
    }


    /// 
    /// 鼠标点击事件
    /// 
    /// 
    /// 
    private void pointersUpdatedHandler(object sender, PointerEventArgs e)
    {
        foreach (var pointer in e.Pointers)
        {
            //Debug.Log(pointer.Id + " touched down at " + pointer.Position);

            //RayHit3DFunction(pointer.Position);
            RayHit2DFunction(pointer.Position);
        }
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/900718.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号