Search code examples
vb.nettimercountdown

Creating Timer Countdown VB.Net?


i am creating a minigame where when the use clicks a button, it "attacks" the monster causing it to lose 5 hp, displayed using a progressbar. then at the same time the monster also attacks making the player lose hp. but the problem is these events happen at the exact same time, and i would like a 2 second interval between the events. ive been trying to get a timer event to work since this morning, but it just wouldnt work here is my code

   Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)           Handles Timer1.Tick

    If Tick = 0 Then
        Timer1.Stop()
        Timer1.Enabled = False
    Else
        Tick -= 1
    End If

End Sub

and here is the attack button event

    Private Sub btnAttack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAttack.Click
    PlayerAttacks(mhealth, attack)
    textShiftUp(numlines)
    HPBarsAlter(mhealth, health)
    Tick = 2
    Timer1.Start()

    MonsterAttacks(health, mattack, CritRate)
    HPBarsAlter(mhealth, health)
    MobDeath(mhealth, MobNumber)

    Timer1.Stop()

End Sub

please tell me if you need any more information thank you :)


Solution

  • Basically, move your monster attack to the timer

    Private Sub btnAttack_Click(...)
        btnAttack.Enabled = False              ' disable more attacks
    
        PlayerAttacks(mhealth, attack)
        textShiftUp(numlines)
        HPBarsAlter(mhealth, health)
    
        MonsterTimer.Interval = 2000
        MonsterTimer.Start()
    End Sub
    
    
    Private Sub MonsterTimer_Tick(...
        ' not sure what the old code was doing
    
         MonsterTimer.Stop           ' stop the attacks
    
         MonsterAttacks(health, mattack, CritRate)
         HPBarsAlter(mhealth, health)
         MobDeath(mhealth, MobNumber)
    
         btnAttack.Enabled = True              ' allow more attacks
    
    End Sub
    

    EDIT Added 2 lines to toggle the ability to attack while waiting.