当前位置:   article > 正文

Unity:在UI上和物体交互_unity ui内的模型交互

unity ui内的模型交互

实现思路
通过计算点击点在ui上的比例,来和标准屏幕上的点建立映射关系,达到交互效果

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

public class Machine_RawImageToMouseClick : MonoBehaviour,IPointerDownHandler, IPointerEnterHandler,IPointerExitHandler
{
    [Tooltip("用于发射射线的相机")]
    public Camera targetCamera;
    public bool isStay;

    public void OnPointerDown(PointerEventData eventData)
    {
        if (Input.GetMouseButtonDown(0)&&isStay)
        {
            Vector3 mouseLocalPos = transform.InverseTransformPoint(Input.mousePosition);
            Vector3 rate = new Vector3(mouseLocalPos.x/GetComponent<RectTransform>().sizeDelta.x , mouseLocalPos.y / GetComponent<RectTransform>().sizeDelta.y, 0);
            Ray ray = targetCamera.ScreenPointToRay(new Vector3(rate.x * 1920, rate.y * 1080,0));
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {

            }
        }
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        isStay = true;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        isStay = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (!isStay||Input.GetMouseButton(0)|| Input.GetMouseButton(1)|| Input.GetMouseButton(2))
        {
            return;
        }
        Vector3 mouseLocalPos = transform.InverseTransformPoint(Input.mousePosition);
        Vector3 rate = new Vector3(mouseLocalPos.x / GetComponent<RectTransform>().sizeDelta.x, mouseLocalPos.y / GetComponent<RectTransform>().sizeDelta.y, 0);
        Ray ray = targetCamera.ScreenPointToRay(new Vector3(rate.x *1920, rate.y * 1080, 0));
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit))
        {

        }
        else
        {

        }
    }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/783212
推荐阅读
相关标签
  

闽ICP备14008679号