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

相关推荐
xiaoshuaishuai82 小时前
C# 接入 OpenClaw
windows·visualstudio·c#
mxwin2 小时前
Unity URP 下抓取当前屏幕内容实现扭曲、镜子与全局模糊效果
unity·游戏引擎·shader
南無忘码至尊7 小时前
Unity学习90天-第2天-认识Unity生命周期函数并用 Update 控制物体移动,FixedUpdate 控制物理
学习·unity·游戏引擎
gihigo19988 小时前
嵌入式幼儿园刷卡系统 (C#实现)
c#
qq_454245039 小时前
通用引用管理框架
数据结构·架构·c#
aq55356009 小时前
三大编程语言深度对比:C# vs 易语言 vs 汇编
开发语言·汇编·c#
光泽雨9 小时前
c# 文件编译的过程
开发语言·c#
zxy28472253019 小时前
使用正运动的仿真软件C#
c#·仿真·运动控制·正运动·无硬件
三省持敬9 小时前
异步并发的“流量警察”:在C#中使用SemaphoreSlim进行并发控制的最佳实践
c#
唐青枫10 小时前
C#.NET IL 中间码 深入解析:从 C# 编译结果到 CLR 执行链路
c#·.net