You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Basic开发类Flappy Bird游戏时PictureBox管道移动不同步问题

问题原因

你的代码核心问题是在For Each遍历Controls集合的过程中直接移除控件:
For Each遍历动态集合时,只要中途删除元素,就会打乱后续的遍历索引,导致部分控件被跳过本次遍历、没有执行移动逻辑。你的顶部管道每次都有概率被跳过,运行时间越长、跳过的次数越多,滞后自然逐步加剧。

修复方案

1. 先拷贝控件集合再遍历

先把需要处理的控件全部拷贝到独立的数组中,再执行遍历逻辑,避免集合动态变化导致的索引异常,修改后的gameloop_Tick代码如下:

Private Sub gameloop_Tick(sender As Object, e As EventArgs) Handles gameloop.Tick
    ' 玩家下落逻辑
    player.Top += 10
    ' 先将所有控件拷贝到独立数组,不受后续移除操作影响
    Dim controlList As Control() = Controls.Cast(Of Control)().ToArray()
    
    For Each c As Control In controlList
        ' 跳过已经被移除的控件
        If c Is Nothing OrElse Not Controls.Contains(c) Then
            Continue For
        End If
        
        ' 管道、计分区移动逻辑
        If c.Tag = "pipe" Or c.Tag = "score" Then
            If c.Left < -40 Then
                Controls.Remove(c)
            Else
                c.Left -= 10
            End If
        End If
        
        ' 碰撞检测逻辑
        If (c.Tag = "collider" Or c.Tag = "pipe") AndAlso player.Bounds.IntersectsWith(c.Bounds) Then
            resetgame()
            Return ' 碰撞后直接结束本次循环,减少无效运算
        End If
        
        ' 计分逻辑
        If c.Tag = "score" AndAlso player.Bounds.IntersectsWith(c.Bounds) Then
            Controls.Remove(c)
            score += 1
            scorelabel.Text = "Score: " & score
        End If
    Next
End Sub

2. 可选优化

你可以单独维护List(Of Control)类型的全局变量,分别存储管道、计分区控件,不用每次遍历所有Controls集合,既提升运行效率,也不会被页面上其他无关控件干扰。

3. 额外检查

确认你生成顶部管道的代码中,控件Tag属性确实设置为"pipe",没有拼写、大小写错误。

内容的提问来源于stack exchange,提问作者xupaii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 15:24:04