英文:
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<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)
}
}
}
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论