2012-09-27 37 views
0

我正在製作一個應用程序,我需要「敵人」來回擺動,如何自動將圖片從左向右移動並重復?Visual Basic - 自動移動圖片

繼承人我當前的代碼。

Private Sub Timer1_Timer() 
    enemy1.Left = enemy1.Left - 5 
End Sub 
+1

您使用哪種語言? – SLaks

+0

正在使用的語言是基本的 – Necrohhh

+0

不。您使用VB6或VB.Net嗎? – SLaks

回答

-1

VB(如C#)應該有一個內置的Timer對象。使用定時器,您應該能夠創建一個事件處理程序,並在設定的時間內觸發,在該功能中,如果您仍然需要,可以移動圖片並重新啓動計時器。

+0

對不起,但這並沒有多大幫助。我對這門語言很陌生,我被告知只需一個計時器就可以做到這一點。 – Necrohhh

+0

我的歉意啊,我恐怕我的VB不太足以提供一個示例。我只知道C#和VB實現幾乎所有相同的功能。如果沒有人提供可接受的答案,您應該能夠在MSDN上找到某些內容。 –

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 
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

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