实现思路
通过计算点击点在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
{
}
}
}