简体   繁体   English

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

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

I am using Canvas in my android game.我在 android 游戏中使用 Canvas。 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.但由于我不是 memory 泄漏的忠实粉丝,所以这不是一个选择。

The canvas rendering system is already double-buffered by design and I have utterly no idea how to fix such a problem. canvas 渲染系统已经设计为双缓冲,我完全不知道如何解决这个问题。 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<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)
            
            }
         }
    }

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:这是一些解释:

Remove elements from collection while iterating 迭代时从集合中移除元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM