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

相关推荐
唐青枫15 小时前
C#.NET ReaderWriterLockSlim 深入解析:读写锁原理、升级锁与使用边界
c#·.net
张老师带你学16 小时前
UnityVR弯曲UI
科技·游戏·unity·游戏引擎·模型
张老师带你学18 小时前
unity作业,街角小场景
科技·游戏·unity·游戏引擎·模型
mxwin21 小时前
Unity Shader LOD:动态 Shader 等级切换技术详解
unity·游戏引擎·shader
ALex_zry21 小时前
C++高性能日志与监控系统设计
c++·unity·wpf
科雷软件测试21 小时前
Midscene.js - AI驱动,带来全新UI自动化体验(安装配置篇)
javascript·人工智能·ui
特立独行的猫a1 天前
OpenHarmony海思WS63星闪平台:LVGL UI框架底层显示驱动移植指南
ui·lvgl·移植·openharmony·驱动·ws63
魔士于安1 天前
Unity太空战舰完整工程,包含战损,实时战损
游戏·unity·游戏引擎·贴图·模型
Nuopiane1 天前
MyPal3(10)视锥体剔除
unity
ghie90901 天前
C# WinForms 条形码生成器(含保存和打印预览功能)
开发语言·c#