C# Unity touch/鼠标碰撞而不是MouseDown()
我有一个精灵,在我发现鼠标点击它的那一刻 但是,我确实需要检测手指或鼠标何时触摸或移动精灵,因为手指/鼠标单击事件将发生在屏幕上的其他位置,而不是精灵顶部C# Unity touch/鼠标碰撞而不是MouseDown(),c#,unity3d,C#,Unity3d,我有一个精灵,在我发现鼠标点击它的那一刻 但是,我确实需要检测手指或鼠标何时触摸或移动精灵,因为手指/鼠标单击事件将发生在屏幕上的其他位置,而不是精灵顶部 public class Hand : MonoBehaviour { private void OnMouseDown() { if (Input.GetMouseButtonDown(0)) { this.transform.gameObject.SetActive
public class Hand : MonoBehaviour
{
private void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
this.transform.gameObject.SetActive(false);
}
}
}
更新:
我试着检测两个触摸精灵和鼠标下降,但我没有得到按钮点击。我可以删除&&Input.GetMouseButtonDown(0)
,如果鼠标移到上面,它会工作,但我希望鼠标/手指都在精灵上,并且按下
private void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000) && Input.GetMouseButtonDown(0))
hit.collider.GetComponent<Button>().onClick.Invoke();
}
private void Update()
{
Ray-Ray=Camera.main.screenpointoray(输入.鼠标位置);
雷卡斯特击中;
if(Physics.Raycast(光线,外击,1000)和&Input.GetMouseButtonDown(0))
hit.collider.GetComponent().onClick.Invoke();
}
有两种可能的解决方案:
第一:不只是使用精灵,而是使用按钮并将其指定给世界空间画布,如图所示
如果您将canva的事件摄影机指定给主摄影机,则此案例触摸应该可以工作
第二:如果你只想使用精灵,那么给它指定一个碰撞器,然后使用光线投射
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
if (Physics.Raycast(ray,out hit,1000))
hit.collider.gameobject.GetComponent<Button>.onClick().Invoke();
Ray-Ray=Camera.main.screenpointoray(Input.GetTouch(i.position));
如果(物理射线投射(射线,命中率,1000))
hit.collider.gameobject.GetComponent.onClick().Invoke();
编辑:如果你有一个按钮组件连接到你的精灵上面的代码将工作。如果不是
就这么叫吧
if(hit.collider.gameobject.GetComponenet<Sprite>())
DoWhateverYouWant()
if(hit.collider.gameobject.GetComponenet())
不管你想要什么
使用EventSystem界面检测任何类型的鼠标与UI元素的交互
列出了EventSystem接口
例如,如果要检测鼠标何时悬停在精灵上,可以向精灵对象添加脚本,如下所示:
using UnityEngine.EventSystems;
using UnityEngine;
public class MouseOverHandler: MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public void OnPointerEnter(PointerEventData data){
Debug.Log("MouseEnter");
}
public void OnPointerExit(PointerEventData data){
Debug.Log("MouseExit");
}
}
请注意,EventSystem与关联精灵画布上的光线投射器一起工作。因此,如果精灵坐在彼此的顶部,它们可以阻止光线投射,因此PointEnter事件只能在最顶部的精灵上触发请尝试重新表述您的问题,我很难理解您想要实现的目标。当然,我已经更新了问题。希望它更清晰一点。听起来如果它移动,你需要从接触点进行光线投射。谢谢,我认为第二个选项最适合我的用例。为了清楚起见,我是否将
射线
附加到精灵的更新
?首先,我编辑了我的答案,第二,为您澄清问题。假设我们有一个名为“TouchController.cs”的脚本,您可以在它的UpdateFunction中写下类似的逻辑。然后,将此脚本附加到场景中的任何游戏对象,并应在手机上启动它。bec它在你的电脑上不起作用,还要确保你检查TouchCount是否超过0我需要一个既能使用鼠标又能使用触摸的解决方案不幸的是,我已经用我认为你所说的更新了我的问题。我已经添加了一个按钮组件,你可以做一些类似的事情,比如#如果统一#安卓然后添加你的触摸逻辑#endif,然后你可以为你的鼠标位置添加普通代码。看看这个: