我目前正在Visual Basic 2010 Express中进行迷宫游戏。我目前正在迷宫中角色的键盘控件上工作。我成功了...有点。我可以使用以下代码来移动Picturebox对象:
Private Sub Lvl1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
Select e.KeyCode
Case Keys.W
Player.Location = New Point(Player.Location.X, Player.Location.Y - 2)
Case Keys.S
Player.Location = New Point(Player.Location.X, Player.Location.Y + 2)
Case Keys.D
Player.Location = New Point(Player.Location.X + 2, Player.Location.Y)
Case Keys.A
Player.Location = New Point(Player.Location.X - 2, Player.Location.Y)
End Select
End Sub
话虽如此,我对结果并不十分满意。当我运行该应用程序时,Picturebox移动得非常缓慢,并且发出错误的信号。最重要的是,它不能沿对角线方向移动。我认为这会使游戏变得非常不切实际,因为用户可能会对像一样的移动速度感到无聊。是否有任何方法可以简单地对Picturebox进行编程,使其以2像素的增量快速且平滑地移动(即在更改方向之前没有延迟)?谢谢!
是的,效果不佳。您需要将键盘事件与控件移动脱开,以便它们可以不同的速率发生。声明两个跟踪上一个用户命令的变量:
Dim xdir, ydir As Integer
可以在KeyDown事件处理程序中轻松设置它们:
Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
Select Case e.KeyCode
Case Keys.W : ydir = -1
Case Keys.A : xdir = -1
Case Keys.S : ydir = 1
Case Keys.D : xdir = 1
End Select
End Sub
在KeyUp事件处理程序中有点棘手,用户不一定会以可预测的顺序释放它们:
Private Sub Form1_KeyUp(sender As Object, e As KeyEventArgs) Handles MyBase.KeyUp
Select Case e.KeyCode
Case Keys.W : If ydir = -1 Then ydir = 0
Case Keys.A : If xdir = -1 Then xdir = 0
Case Keys.S : If ydir = 1 Then ydir = 0
Case Keys.D : If xdir = 1 Then xdir = 0
End Select
End Sub
现在,您需要一个使用这些命令来实现控件移动的“游戏循环”。这可以像计时器一样简单,将时间间隔设置为15或31毫秒即可获得可预测的更新速率。
Dim velocity As Integer = 4
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim newx = PictureBox1.Location.X + velocity * xdir
newx = Math.Min(Math.Max(0, newx), Me.ClientSize.Width - PictureBox1.Width)
Dim newy = PictureBox1.Location.Y + velocity * ydir
newy = Math.Min(Math.Max(0, newy), Me.ClientSize.Height - PictureBox1.Height)
PictureBox1.Location = New Point(newx, newy)
End Sub
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句