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

相关推荐
ghost1432 小时前
C#学习第29天:表达式树(Expression Trees)
开发语言·c#
派阿喵搞电子8 小时前
在UI界面内修改了对象名,在#include “ui_mainwindow.h“没更新
c++·qt·ubuntu·ui
pop_xiaoli10 小时前
OC—UI学习-2
学习·ui·ios
安木夕12 小时前
C#-Visual Studio宇宙第一IDE使用实践
前端·c#·.net
gregmankiw15 小时前
C#调用Rust动态链接库DLL的案例
开发语言·rust·c#
XR-AI-JK15 小时前
Unity VR/MR开发-VR/开发SDK选型对比分析
unity·vr·mr
阿蒙Amon16 小时前
06. C#入门系列【自定义类型】:从青铜到王者的进阶之路
开发语言·c#
钢铁男儿20 小时前
C# 表达式和运算符(表达式和字面量)
开发语言·c#
林鸿群20 小时前
C#子线程更新主线程UI及委托回调使用示例
开发语言·c#
o0向阳而生0o20 小时前
63、.NET 异常处理
c#·.net·异常处理