Welcome! In this episode, I am going to attempt to make the character animate while he is walking... also I am going to prevent him from walking off the edge of the form. First, let's do the animation: We are going to need a cycler for the animation. One of the tricky parts of animation is coordinating the animation cycler number with the display and the program execution. Here, it will be simple: while the button is pressed, we will update the cycler. When the buttons are released, the cycler will reset. Usually, the counter will be updated something like this: Cycler = (Cycler + 1) Mod NumberOfFrames Since the NumberOfFrames is four (if you look at the bitmap from the previous section, our Cycler will be like: Cycler = (Cycler + 1) Mod 4 And since Mod 4 is equivalent to And 3, we can do this. Cycler = (Cycler + 1) And 3 But, I'm going to pretend that I don't know if this is going to be the final picture. Instead, I'll make it a constant. So, here is what we add:
Dim AnimCycler As Integer 'This is the animation cycler that will count from 0 to 3 and back to 0. Const WALKINGFRAMECOUNT As Integer = 4 'How many frames are in each walking cycle. |
New Rectangle(CHARWIDTH * (CharDirec << 2), 0, CHARWIDTH, CHARHEIGHT) becomes New Rectangle(CHARWIDTH * CharDirec * WALKINGFRAMECOUNT, 0, CHARWIDTH, CHARHEIGHT) |
'Now, update the animation cycler. AnimCycler = (AnimCycler + 1) Mod WALKINGFRAMECOUNT |
If Not (GoLeft OrElse GoRight) Then 'If neither key is pressed. AnimCycler = 0 'Reset the counter, and signal another redraw. UpdateArtwork = True End If |
New Rectangle(CHARWIDTH * CharDirec * WALKINGFRAMECOUNT, 0, CHARWIDTH, CHARHEIGHT) |
New Rectangle(CHARWIDTH * CharDirec * WALKINGFRAMECOUNT + AnimCycler * CHARWIDTH, 0, CHARWIDTH, CHARHEIGHT) |
GFX.DrawImage(PlayerBmp, PlayerLoc.X, PlayerLoc.Y, New Rectangle(CHARWIDTH * CharDirec * WALKINGFRAMECOUNT + AnimCycler * CHARWIDTH, 0, CHARWIDTH, CHARHEIGHT), GraphicsUnit.Pixel) |
If PlayerLoc.Left < 0 Then 'If the player goes off the edge of the form, then we will move him back to the edge. PlayerLoc.Offset(-PlayerLoc.Left, 0) End If |
If PlayerLoc.Right > MAPWIDTH Then 'If player goes off right edge... move him back. PlayerLoc.Offset(MAPWIDTH - PlayerLoc.Right, 0) End If |
If GoLeft Then PlayerLoc.Offset(-MOVESPEED, 0) 'Move player left. If PlayerLoc.Left < 0 Then 'If the player goes off the edge of the form, then we will move him back to the edge. PlayerLoc.Offset(-PlayerLoc.Left, 0) End If UpdateArtwork = True CharDirec = 0 'Look left. 'Now, update the animation cycler. AnimCycler = (AnimCycler + 1) Mod WALKINGFRAMECOUNT ElseIf GoRight Then PlayerLoc.Offset(MOVESPEED, 0) 'Move player right. If PlayerLoc.Right > MAPWIDTH Then 'If player goes off right edge... move him back. PlayerLoc.Offset(MAPWIDTH - PlayerLoc.Right, 0) End If UpdateArtwork = True CharDirec = 1 'Look right. 'Now, update the animation cycler. AnimCycler = (AnimCycler + 1) Mod WALKINGFRAMECOUNT End If |