0

我正在尝试在按钮被注视时为其设置动画。我有以下代码,我在其中从球体中投射光线以找到它击中的按钮。

var eventDataCurrentPosition = new PointerEventData(EventSystem.current);
        eventDataCurrentPosition.position = screenPosition;

var results = new List<RaycastResult>();

EventSystem.current.RaycastAll(eventDataCurrentPosition, results);

foreach (var result in results)
{
     Debug.Log(result.gameObject.name);
}  

为了为按钮设置动画,我将以下代码添加到按钮中。不幸的是,OnPointerEnter永远不会调用 or ``OnPointerExit。

[RequireComponent(typeof(Button))]
public class InteractiveItem : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    public Image  progressImage;
    public bool   isEntered = false;
    RectTransform rt;
    Button        _button;
    float         timeElapsed;
    Image         cursor;
    float         GazeActivationTime = 5;

// Use this for initialization
void Awake()
{
    _button = GetComponent<Button>();
    rt      = GetComponent<RectTransform>();
}


void Update()
{
    if (isEntered)
    {
        timeElapsed              += Time.deltaTime;
        progressImage.fillAmount =  Mathf.Clamp(timeElapsed / GazeActivationTime, 0, 1);
        if (timeElapsed >= GazeActivationTime)
        {
            timeElapsed = 0;
            _button.onClick.Invoke();
            progressImage.fillAmount = 0;
            isEntered                = false;
        }
    }
    else
    {
        timeElapsed = 0;
    }
}

#region IPointerEnterHandler implementation

public void OnPointerEnter(PointerEventData eventData)
{
    CodelabUtils._ShowAndroidToastMessage("entered");
    isEntered = true;
}

#endregion

#region IPointerExitHandler implementation

public void OnPointerExit(PointerEventData eventData)
{
    CodelabUtils._ShowAndroidToastMessage("exit");

    isEntered                = false;
    progressImage.fillAmount = 0;
}

#endregion
}

我错过了什么吗?还是有其他方法可以实现这一目标?

4

1 回答 1

1

我猜你的 Raycast 应该会触发OnPointerEnter所有结果。

您将需要使用ExecuteEvents.Execute例如

ExecuteEvents.Execute(result.gameObject, eventDataCurrentPosition, ExecuteEvents.pointerEnterHandler);

并且在某些时候也必须调用pointerExitHandler.

因此,我会存储一个 HashSet 之类的

using System.Linq;

private HashSet<GameObject> previousEnters = new HashSet<GameObject>();

...

foreach (var result in results.Select(r => r.gameObject))
{
    Debug.Log(result.name);
    ExecuteEvents.Execute(result, eventDataCurrentPosition, ExecuteEvents.pointerEnterHandler);
    // Store the item so you can later invoke exit on them
    if(!previousEnters.Contains(result)) previousEnters.Add(result);
}  

// This uses Linq in order to get only those entries from previousEnters that are not in the results
var exits = previousEnters.Except(results);
foreach(var item in exits)
{
    if(item) ExecuteEvents.Execute(item, eventDataCurrentPosition, ExecuteEvents.pointerExitHandler);
}

您可能实际上想要实现自己的 custom PointerInputModule


替代/示例

作为初学者,您还可以使用我不久前对Using Raycast 而不是 Gaze Pointer的回答,我创建了一个基于 Steam 的 VR Laserpointer 的脚本,该脚本允许与 3D 对象和 UI 元素进行交互。


注意:在智能手机上输入,但我希望这个想法很清楚

于 2020-02-07T15:51:01.087 回答