我正在制作一个应用程序,我需要“敌人”来回踱步,我如何自动将图片从左向右移动并重复?
这是我目前的代码。
Private Sub Timer1_Timer()
enemy1.Left = enemy1.Left - 5
End Sub
答案 0 :(得分:1)
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 :(得分:0)
我现在承认我的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
答案 2 :(得分:0)
你也可以使用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
答案 3 :(得分:-1)