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对象,推荐使用第三种方法。

相关推荐
我是唐青枫8 分钟前
深入理解 C#.NET IEnumerable<T>:一切集合的起点
c#·.net
2501_9307077822 分钟前
使用C#代码重新排列 PDF 页面
开发语言·pdf·c#
zxy284722530128 分钟前
利用C#的视觉库Halcon识别药盒多条形码,可用于追溯码识别(二)
c#·halcon·条码·追溯码·多条码
Thomas_YXQ37 分钟前
Unity3D IL2CPP如何调用Burst
开发语言·unity·编辑器·游戏引擎
航Hang*39 分钟前
Photoshop 图形与图像处理技术——第2章:图像处理基础
图像处理·笔记·ui·组合模式·photoshop
mudtools44 分钟前
当传统工单遇见飞书:.NET系统的协作升级之旅
c#·自动化·.net·飞书
唐青枫1 小时前
深入理解 C#.NET Interlocked.Increment:原子操作的核心
c#·.net
钰fly9 小时前
C#异常处理 递归算法
c#
ejjdhdjdjdjdjjsl10 小时前
JSON序列化与反序列化实战指南
数据库·microsoft·c#
UI设计兰亭妙微12 小时前
医疗设备UI设计核心准则与案例拆解——以临床场景为核心的专业设计逻辑
ui·用户体验设计·移动端界面设计