Android游戏 – 当从列表中移除实体时屏幕闪烁

huangapple go评论79阅读模式
英文:

Android Game - Screen Flickers When an Entity Removed From The List

问题

以下是您要翻译的内容:

我在我的安卓游戏中使用Canvas。当我从实体列表中移除一个不再显示的实体时,所有其他实体会在短暂的时间内闪烁。如果不移除它,则没有这样的问题。但因为我不是内存泄漏的铁杆粉丝,这不是一个选项。

画布渲染系统已经通过设计进行了双缓冲处理,我完全不知道如何解决这样的问题。我曾经想过也许是因为项目移除后列表在对自身进行排序,于是尝试将其更改为Set,但那也不起作用。

是否有人知道为什么会发生这种情况以及如何解决呢?

代码结构:

private val gameObjects: List<GameObject> = mutableListOf()
    
fun update(deltaTime: Long)
{
    gameObjects.forEach {
        it.update(deltaTime)
    }
}

fun render(canvas: Canvas)
{
    gameObjects.forEach {
        when (getVisibilityStatus(it.virtualY))
        {
            VisibilityStatus.VISIBLE -> it.render(canvas, virtualToPhysicalY(it.virtualY))

            VisibilityStatus.BELOW_SCREEN ->
            {
                if (virtualToPhysicalY(it.virtualY) > screenSizePairXY.second)
                    gameObjects.remove(it)
                
            }
        }
    }
}
英文:

I am using Canvas in my android game. When I remove a no longer displayed entity in my entity list, all other entities are flickering for a brief time. When it's not removed, there is no such problem. But since I am not a big fan of memory leaks, that's not an option.

The canvas rendering system is already double-buffered by design and I have utterly no idea how to fix such a problem.
I have thought maybe it is because the list is sorting itself after the item removal and tried changing it to a Set, but that didn't work either.

Does anyone have any idea why this might be happening and how to fix it?

Structure of the code:

private val gameObjects: List&lt;GameObject&gt; = mutableListOf()
    
    fun update(deltaTime: Long)
    {
        gameObjects.forEach {
            it.update(deltaTime)
    }

 fun render(canvas: Canvas)
    {
      gameObjects.forEach {
         when (getVisibilityStatus(it.virtualY))
         {
            VisibilityStatus.VISIBLE -&gt; it.render(canvas, virtualToPhysicalY(it.virtualY))

            VisibilityStatus.BELOW_SCREEN -&gt;
            {
              if (virtualToPhysicalY(it.virtualY) &gt; screenSizePairXY.second)
                gameObjects.remove(it)
            
            }
         }
    }

答案1

得分: 2

从正在迭代的列表中删除元素并不安全。最好是在绘制循环之前,在单独的循环中执行修剪(删除不可见元素)。以下是一些解释:

https://stackoverflow.com/questions/10431981/remove-elements-from-collection-while-iterating

英文:

Removing elements from list you iterating its not safe practice. It would be better to do culling (removing invisible elements) before drawing cycle in separate cycle. Here is some explanation:

https://stackoverflow.com/questions/10431981/remove-elements-from-collection-while-iterating

huangapple
  • 本文由 发表于 2020年9月1日 11:15:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63680827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定