15

我正在为 Android 开发游戏。它发生了很多事情,但运行得相当顺利。也就是说,当然,直到用户触摸屏幕。

当他们触摸它时,大约每十毫秒onTouchEvent调用一次(使用action = ACTION_MOVE,x = 0和),这似乎是一个相当高的优先级,因为它完全消除了帧速率。y = 0一旦触摸结束,帧速率就会恢复到其良好状态。

我试过了

  • 像往常onTouchEvent一样处理游戏输入
  • 立即onTouchEvent返回_true
  • 根本没有onTouchEvent实施

该问题在所有三种情况下都存在。

有没有人遇到过这个?有没有办法降低ACTION_MOVE事件的生成率,或者确保它们仅在实际移动时生成,或者使用仅获取当前触摸位置的轮询方法?或者甚至只是一种完全禁用它的方法?

4

5 回答 5

14

阅读此线程。基本上你想要让事件线程休眠,否则系统会发送很多你需要处理的事件(在 x,y 和压力之间总是有一些运动发生)。

于 2009-04-27T17:43:53.397 回答
1

我一直在努力关注你们一直在谈论的一切,但我必须承认,在尝试了几种实施你们建议的方法之后,我仍然无法取得任何积极的结果。你们中的一个可以提供一些示例代码吗?具体来说,我想知道如何让主/ UI 线程进入睡眠状态。如果它适用于我的游戏,那么知道如何建立一个像 Jon 实现的投票模型也会很高兴。

这是我的代码的样子。在 UI 线程上:

public boolean onTouchEvent(MotionEvent event) {
    // Store event somewhere the game thread can see it:
    // ...

    synchronized (someObject) {
        try {
            someObject.wait(1000L);
        } catch (InterruptedException e) {
        }
    }

    return true;
}

在游戏线程上:

void myGame() {
    while (!stopping) {
        // ...

        // Get a touch event:
        synchronized (someObject) {
            someObject.notify();
        }
        Thread.yield();

        // ...
    }
}
于 2010-01-01T14:32:36.627 回答
0

也许是一个有点明显的解决方案,但是......您是否尝试过仅处理其中的 1/10?如果您在 UI 线程上每 10 毫秒触发一次处理,那可能会减慢帧速率,是的。那么,如果您只是累积一个计数器,并且仅在超过某个最小阈值时才进行任何处理呢?

于 2009-04-27T13:09:00.780 回答
0

If you want a solution without having to deal with synchronizing threads I can recommend using the Handler interface to send the event and relevant data using a Message/Bundle to the game rendering thread. The sleep workaround hinted here still applies.

于 2011-11-14T19:20:56.100 回答
0

Generally events comes with a timestamp property so it's easy to compute and throttle event rate.

if (currentEventTimestamp - lastEventTimestamp > 500) { 

    lastEventTimestamp = currentEventTimestamp;

    // do something 

}

于 2014-11-24T14:19:40.293 回答