我一直在绞尽脑汁,使用我能想到的每一个谷歌搜索词组,但还没有找到解决方案。
我有一个带有 3D 场景和漂浮在上面的 UI 元素的 Unity 应用程序。有一个 UI 元素是 protractor 的图像。该图像需要在场景周围进行药物,旋转和缩放。所有这些都有效,唯一的问题是,无论用户触摸 protractor 还是其他地方, protractor 总是会使用react。
我开始寻找与 Swift 的 someCGRect.contains(someCGPoint)
类似的东西。这样我就可以忽略任何不在 protractor 范围内的东西。图像似乎没有这样的属性,所以我做了很多其他搜索。
我终于找到了这个视频; https://www.youtube.com/watch?v=sXc8baUK3iY那基本上就是我要找的东西……除了不起作用。
该视频使用碰撞器和刚体,然后在代码中检查碰撞器是否与接触点重叠。看起来正是我需要的。不幸的是,无论它们在哪里,都不会与对撞机重叠。经过一番Debug.Log
我发现对撞机的范围报告为 (0, 0, 0)
.这显然是为什么没有任何触摸与其重叠的原因,但我不知道如何使范围不是 0。
这是附加到图像的对撞机和刚体的信息:
有一个按钮可以使用以下代码打开和关闭 protractor :
public void toggle() {
this.enabled = !this.enabled;
this.gameObject.SetActive(this.enabled);
}
protractor 开始时可见但
Start()
来电toggle()
立即开始,因此用户将其视为开始。这是执行测试以查看是否应响应触摸的代码:
void checkTouches() {
if (Input.touchCount <= 0) {
return;
}
bool oneTouchIn = false;
Collider2D collider = GetComponent<Collider2D>();
Debug.Log("🔵 The bounds of the collider are: " + collider.bounds);
// The above always logs the extents as (0,0,0).
foreach (Touch touch in Input.touches) {
Vector2 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
if(collider.OverlapPoint(touchPos)) {
// Since the extents are all 0 we never find any overlaps
oneTouchIn = true;
break;
}
}
if (!oneTouchIn) {
return; // Always ends up here
}
// We must have at least one touch that is in our bounds.
// Do stuff with the touch(es) here…
}
自从 SDK 发布以来,我一直在使用 Objective-C 进行 iOS 开发,自从它问世以来,我一直在使用 Swift,但我对 Unity 还是很陌生。我确定问题是我错过了一些愚蠢的东西,但我找不到它。
有谁知道我缺少什么以使当前版本正常工作或仅响应有界触摸的替代方式?
最佳答案
Image doesn't seem to have such a property
没有
Image
组件本身没有那个...但是
rect
RectTransform
的属性(property)组件每个 UI GameObject
拥有。它被称为 Contains .所以你可以做例如
RectTransform imgRectTransform = imageObject.GetComponent<RectTransform>();
Vector2 localTouchPosition = imgRectTransform.InverseTransformPoint(Touch.position);
if (imgRectTransform.rect.Contains(localToichPosition)) { ... }
或者,您可以使用 IPointerEnterHandler和 IPointerExitHandler目标图像上组件中的接口(interface),例如
public class DragableHandler : MonkBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public bool IsHover {get; private set; }
//Detect if the Cursor starts to pass over the GameObject
public void OnPointerEnter(PointerEventData pointerEventData)
{
//Output to console the GameObject's name and the following message
Debug.Log("Cursor Entering " + name + " GameObject");
IsHover = true;
}
//Detect when Cursor leaves the GameObject
public void OnPointerExit(PointerEventData pointerEventData)
{
//Output the following message with the GameObject's name
Debug.Log("Cursor Exiting " + name + " GameObject");
IsHover = false;
}
}
而不是在你的脚本中检查它使用
if(imageObject.GetComponent<DragableHandler>().IsHover) { ... }
还要确保我们
EventSystem
您还可以添加 Touch Input Module
并检查标志 Force Module Active
.
关于ios - 我如何只响应 UI 图像中的触摸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54947628/