VisualFreeBasic游戏趣味编程_8.2_鼠标交互

2026-1-22 / 0 评论 / 50 阅读

回顾7.4节中讲解的键盘交互处理函数:

Sub updateWithInput(moveDirection As String) ' 和输入有关的更新
   If IsKeyPress(&H57) Then
      moveDirection = "上"
   ElseIf IsKeyPress(&H53) Then
      moveDirection = "下"
   ElseIf IsKeyPress(&H41) Then
      moveDirection = "左"
   ElseIf IsKeyPress(&H44) Then
      moveDirection = "右"
   End If
End Sub

对于很多游戏,鼠标交互是一种更加自然的交互方式。和键盘交互代码结构类似,我们也可以实现基于鼠标的交互处理:

Sub updateWithInput() ' 和输入有关的更新
   If IsKeyPress(VK_LBUTTON) Then '鼠标左键点击
      Dim ps As Point
      GetCursorPos(@ps) '获取鼠标位置
      '执行相应的操作
      'ps.x 当前鼠标的x坐标 ps.y  为当前鼠标的y坐标
   End If

End Sub

以下代码实现点击鼠标时,在鼠标位置绘制一个红色圆圈:

Sub 游戏执行过程(hWndForm As hWnd)
   Dim gg As yGDI = hWndForm
   Do
      If IsKeyPress(VK_LBUTTON) Then '鼠标左键点击
         Dim ps As Point
         GetCursorPos(@ps) '获取鼠标在屏幕的位置
         MapWindowPoints HWND_DESKTOP, hWndForm, @ps, 1  '将鼠标位置从屏幕转换到游戏窗口的位置
         ps.x = DpiUnScaleI(ps.x) '响应系统DPI
         ps.y = DpiUnScaleI(ps.y)
         gg.Brush BGR(229, 0, 0) 'GDI的颜色值。
         gg.DrawEllipse ps.x - 10, ps.y - 10, 20, 20 '画小圆圈
         gg.Redraw
      End If
      Sleep 10
   Loop
End Sub

程序运行后输出如图所示。

同样,也可以实现鼠标移动时,绘制一系列绿色的小圆圈:

Sub 游戏执行过程(hWndForm As hWnd)
   Dim gg As yGDI = hWndForm
   Do
      Dim ps As Point
      GetCursorPos(@ps) '获取鼠标在屏幕的位置
      MapWindowPoints HWND_DESKTOP, hWndForm, @ps, 1 '将鼠标位置从屏幕转换到游戏窗口的位置
      If ps.x >= 0 and ps.x <= Form1.ScaleWidth And ps.y >= 0 and ps.y < Form1.ScaleHeight then
         ps.x = DpiUnScaleI(ps.x) '响应系统DPI
         ps.y = DpiUnScaleI(ps.y)

         gg.Brush BGR(0, 204, 0) 'GDI的颜色值。
         gg.DrawEllipse ps.x - 5, ps.y - 5, 10, 10 '画小圆圈
         gg.Redraw
      End If
      Sleep 10
   Loop
End Sub

评论一下?

OωO
取消