unity里鼠标位置是否在物体上。

1. 使用Raycast

如果你的图片是在UI Canvas上,可以使用Raycast来检测鼠标点击是否在图片上。

using UnityEngine;

using UnityEngine.EventSystems;

using UnityEngine.UI;

public class ImageClickChecker : MonoBehaviour

{

public Image targetImage;

void Update()

{

if (Input.GetMouseButtonDown(0))

{

if (IsPointerOverUIObject(targetImage.gameObject))

{

Debug.Log("Mouse is over the image!");

}

else

{

Debug.Log("Mouse is not over the image.");

}

}

}

private bool IsPointerOverUIObject(GameObject target)

{

PointerEventData pointerEventData = new PointerEventData(EventSystem.current);

pointerEventData.position = Input.mousePosition;

List<RaycastResult> results = new List<RaycastResult>();

EventSystem.current.RaycastAll(pointerEventData, results);

foreach (RaycastResult result in results)

{

if (result.gameObject == target)

{

return true;

}

}

return false;

}

}

2. 使用RectTransform Utility

另外一种方法是直接使用RectTransformUtility来进行坐标转换和检测。

using UnityEngine;

using UnityEngine.UI;

public class ImageClickChecker : MonoBehaviour

{

public Image targetImage;

void Update()

{

if (Input.GetMouseButtonDown(0))

{

if (IsMouseOverImage(targetImage))

{

Debug.Log("Mouse is over the image!");

}

else

{

Debug.Log("Mouse is not over the image.");

}

}

}

private bool IsMouseOverImage(Image image)

{

RectTransform rectTransform = image.GetComponent<RectTransform>();

Vector2 localMousePosition = RectTransformUtility.ScreenPointToLocalPointInRectangle(

rectTransform, Input.mousePosition, null, out Vector2 localPoint);

return rectTransform.rect.Contains(localPoint);

}

}

3. 使用Collider和Physics Raycast

如果你的图片是3D对象,使用Collider和Physics Raycast可以更容易实现。

using UnityEngine;

public class ImageClickChecker : MonoBehaviour

{

void Update()

{

if (Input.GetMouseButtonDown(0))

{

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

RaycastHit hit;

if (Physics.Raycast(ray, out hit))

{

if (hit.collider != null && hit.collider.gameObject == this.gameObject)

{

Debug.Log("Mouse is over the image!");

}

else

{

Debug.Log("Mouse is not over the image.");

}

}

}

}

}

根据你的具体需求,选择适合的检测方法。如果你的图片在Canvas上,推荐使用第一种或第二种方法;如果你的图片是3D对象,推荐使用第三种方法。

相关推荐
A_nanda几秒前
vue快速学习框架
前端·javascript·vue.js·学习·c#
晚霞的不甘27 分钟前
Flutter for OpenHarmony《智慧字典》中的沉浸式学习:成语测试与填空练习等功能详解
学习·flutter·ui·信息可视化·前端框架·鸿蒙
Eiceblue1 小时前
通过 C# 解析 HTML:文本提取 + 结构化数据获取
c#·html·.net·visual studio
l1t1 小时前
在Windows的WSL中试用GizmoSQL UI连接GizmoSQL数据库服务器
数据库·windows·ui
jtymyxmz2 小时前
《Unity Shader》14.1 卡通风格的渲染
unity·游戏引擎
SunnyDays10112 小时前
使用 C# 将 Excel XLSX 或 XLS 转换为 HTML:完整指南
c#·excel转html·xlsx转html·xls转html
时光追逐者2 小时前
一款基于 .NET Avalonia 开源免费、快速、跨平台的图片查看器
c#·.net·图片查看器
CamilleZJ2 小时前
多端ui方案
前端·ui
天人合一peng2 小时前
unity获得和修改button的text(TMP)
java·前端·unity
dzj202111 小时前
Unity中使用LLMUnity遇到的问题(三)——如何配置和使用知识库
unity·llmunity·知识库大模型