Aaron York
Aaron York

Reputation: 37

Stop Select Case from repeating in VB

I'm sorry the title was vague, I didn't know how to explain this problem concisely.

I have this bit of code, here:

Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        Select Case e.KeyCode
            Case Keys.Left
                pBox1.Visible = False
                pBox3.Visible = False
                pBox2.Visible = True
                Me.pBox1.Left -= 3
                Me.pBox2.Left -= 3
                Me.pBox3.Left -= 3
                Me.pBox4.Left -= 3
            Case Keys.Right
                pBox1.Visible = False
                pBox3.Visible = False
                pBox2.Visible = True
                Me.pBox1.Left += 3
                Me.pBox2.Left += 3
                Me.pBox3.Left += 3
                Me.pBox4.Left += 3
            Case Keys.E
                pBox2.Visible = False
                pBox3.Visible = False
                pBox1.Visible = True
            Case Keys.Up
                pBox4.Visible = True
                pBox3.Visible = False
                pBox2.Visible = False
                pBox1.Visible = False
                Me.pBox4.Top -= 3
                Me.pBox3.Top -= 3
                Me.pBox2.Top -= 3
                Me.pBox1.Top -= 3


        End Select
    End Sub

This works fine, the different pBoxes represent the different picture boxes I want to move. Everything works, the picture boxes move left/right/up, but I want to stop the 'up' one from repeating (I am making a video game character move to the left/right/jump) so the player can't just float into the air. I want the 'Case Keys.Up' to only repeat once, so it works like a proper jumping mechanic, or something like that. Does anyone know how to do this? Any answers are appreciated, thanks in advance!

-Aaron

Upvotes: 0

Views: 89

Answers (1)

laancelot
laancelot

Reputation: 3207

Your question is more complicated than you might think. The thing is, you don't need a snippet of code. You need a new way to look at your code.

What you want is a design pattern named "States".

Here's a link, just for you.

Just to help you start, here's some pointers. Your character can do many things. You can divide those things in states. Maybe your character can stay idle, walk, run, jump, fall and die. All of these are states, and by enforcing those states you kinda have a mask that will "change the rules" your character abides for any of these instances. For an example, your character may have different animations for every one of these states. It's max speed might be different for these, too. Maybe he becomes vulnerable or invincible in some situations.

By enforcing states, you create a strict structure around your character's behavior, which is both easier to custom and harder to make exceptions to. Most games use this pattern a lot.

Good programming!

Upvotes: 2

Related Questions