我正在创建一个程序,让你的角色必须沿着迷宫前进。
如何阻止他穿过墙壁? (墙壁和角色都是图片框)。即当你按向上键时,if there is a wall in front of him,他没有移动。目前,我的代码只更改了图片框的X和Y值,因此角色在墙上/墙上移动。这是在Visual Basic 2010中。有没有办法扫描图片框的标签,如果它是一个cerain值,不移动? 到目前为止我的移动代码是:
Private Sub frmLevel1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
If Tag <= 2 Then
Select Case e.KeyCode
Case Keys.Up
picP1.Top -= 36
Case Keys.Right
picP1.Left += 36
Case Keys.Down
picP1.Top += 36
Case Keys.Left
picP1.Left -= 36
Case Keys.W
picP2.Top -= 36
Case Keys.D
picP2.Left += 36
Case Keys.S
picP2.Top += 36
Case Keys.A
picP2.Left -= 36
End Select
End If
End Sub
这会在按下的方向上移动角色1网格空间。 我还有一个计时器,可以阻止角色移过外边框:
Private Sub tmrBorders_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrBorders.Tick
If picP1.Left <= 39 Then
picP1.Left += 36
End If
If picP1.Left >= 583 Then
picP1.Left -= 36
End If
If picP1.Top <= 83 Then
picP1.Top += 36
End If
If picP1.Top >= 445 Then
picP1.Top -= 36
End If
If picP2.Left <= 39 Then
picP2.Left += 36
End If
If picP2.Left >= 583 Then
picP2.Left -= 36
End If
If picP2.Top <= 83 Then
picP2.Top += 36
End If
If picP2.Top >= 445 Then
picP2.Top -= 36
End If
End Sub
我只是内心边界有问题。有可能有办法扭转运动方向吗?或者记录角色所在的最后一个空格?
答案 0 :(得分:0)
MSDN继承说明链接:msdn.microsoft.com/en-us/library/ms973803.aspx
也许是这样的?
不使用标准图片框,而是创建自己的类,该类继承自图片框。
Public Class MYPICBOX
inherits picturebox
end class
然后添加一些属性以显示它无法通过
Public Class MYPICBOX
inherits picturebox
Property IsImpassable as Boolean = true
end class
使用MYPICBOX类替换图片框
填充您的世界现在测试你是否可以通过它
Sub MoveIfNoCollision(spriteToMove as mypicbox, Xmovement as integer, YMovement as integer)
'Variable to determine if the actual movement routine should be called
collision = False
'for this next bit of code, you should use something like a rectangle to artificially expand the bounds of the
'sprite to move and perform your check using it instead of the sprite to move object.
'or you could move it, run this check and then move it back if
'a collision is detected.
'check each mypicbox that is not the one targeted for movement
For Each pb as mypicbox In Me.Controls
If pb IsNot spriteToMove AndAlso spriteToMove.Bounds.IntersectsWith(pb.Bounds) andalso pb.impassable Then
'shouldn't move, mark it as failed and end the sub
collision = True
Exit For
end if
Next
IF collision = false
'safe to move. Call the actual move routine
MoveSpriteAndUpdateImage(spriteToMove, Xmovement, YMovement)
end if
end sub
编辑:
Sub MoveSpriteAndUpdateImage(spriteToMove as mypicbox, Xmovement as integer, YMovement as integer)
'do stuff if needed prior to moving
'Move
spriteToMove.location = New Point(spriteToMove.location.X + XMovement, spriteToMove.location.Y + Ymovement)
'do stuff if needed after moving
endsub