我正在制作一个应用程序,我需要“敌人”来回摆动,如何自动将图片从左向右移动并重复?Visual Basic - 自动移动图片
继承人我当前的代码。
Private Sub Timer1_Timer()
enemy1.Left = enemy1.Left - 5
End Sub
我正在制作一个应用程序,我需要“敌人”来回摆动,如何自动将图片从左向右移动并重复?Visual Basic - 自动移动图片
继承人我当前的代码。
Private Sub Timer1_Timer()
enemy1.Left = enemy1.Left - 5
End Sub
VB(如C#)应该有一个内置的Timer对象。使用定时器,您应该能够创建一个事件处理程序,并在设定的时间内触发,在该功能中,如果您仍然需要,可以移动图片并重新启动计时器。
对不起,但这并没有多大帮助。我对这门语言很陌生,我被告知只需一个计时器就可以做到这一点。 – Necrohhh
我的歉意啊,我恐怕我的VB不太足以提供一个示例。我只知道C#和VB实现几乎所有相同的功能。如果没有人提供可接受的答案,您应该能够在MSDN上找到某些内容。 –
我承认现在我的VB是生锈的。自从我使用它10年以来。我没有办法测试这个代码,但我认为这个示例应该让你关闭,或者至少让你指出正确的方向。
Private Sub Timer1_Timer()
Do
enemy1.Left = enemy1.Left - 5
If enemy1.Left = < 5 Then
Do
enemy1.Right = enemy1.Right + 5
Loop Until enemy1.Right = > 1000 'or whatever your size is
End If
Loop
End Sub
Option Explicit
Const nTwipsPerMove = 15
Private Sub Timer1_Timer()
Static strDirection As String
If strDirection = "" Then strDirection = "left"
If enemy.Left > 0 Then
If strDirection = "left" Then
enemy.Left = enemy.Left - nTwipsPerMove
ElseIf strDirection = "right" Then
enemy.Left = enemy.Left + nTwipsPerMove
End If
End If
If enemy.Left = 0 Then
If strDirection = "left" Then strDirection = "right"
enemy.Left = enemy.Left + nTwipsPerMove
End If
If enemy.Left + enemy.Width = Me.Width - nTwipsPerMove * 5 Then
If strDirection = "right" Then strDirection = "left"
enemy.Left = enemy.Left - nTwipsPerMove
End If
End Sub
nTwipsPerMove
意味着多少缇在每个循环移动 Timer1.Interval = 10
你也可以使用1个变量它的速度,并使其负面当敌人有移动另一种方式
'1 form with :
' 1 timer : name=Timer1
' 1 picturebox : name=Picture1
Option Explicit
Private msngStep As Single
Private Sub Form_Load()
Timer1.Interval = 200 'delay in milliseconds between steps
msngStep = ScaleWidth/20 'step size, and direction
End Sub
Private Sub Timer1_Timer()
Dim sngX As Single
With Picture1 'the enemy
sngX = .Left + msngStep 'calculate new position
If (sngX < 0) Or (sngX > (ScaleWidth - .Width)) Then 'check boundary
msngStep = msngStep * -1 'adjust direction
sngX = sngX + 2 * msngStep 'keep enemy inside
End If
.Left = sngX 'move to new position
End With 'Picture1
End Sub
您使用哪种语言? – SLaks
正在使用的语言是基本的 – Necrohhh
不。您使用VB6或VB.Net吗? – SLaks