Computer Science Canada Having troubles moving sprite across the screen using the arrow keys? |
Author: | CookieMonster [ Sat Nov 02, 2013 10:30 am ] | ||||
Post subject: | Having troubles moving sprite across the screen using the arrow keys? | ||||
Hi I'm having trouble with moving the sprite across the screen, the sprite move but it's not smooth. For example when I press the right arrow key the sprite moves on the spot, but shifts right after the 'loop'. I don't know how to explain this but i hope you understand this is my code:
What's wrong with it? D: Mod Edit: Please wrap you code in either of the following in order to preserve whitespace (indentation) and to highlight the syntax.
|
Author: | Zren [ Sat Nov 02, 2013 11:50 am ] | ||||||||||
Post subject: | RE:Having troubles moving sprite across the screen using the arrow keys? | ||||||||||
You should only be drawing one complete picture (frame) for each iteration of the main game loop. I'll provide an example after this next bit. Since having animations play as you move is slightly more complicated, let's first work our way up to that point. Step 1: Draw a black box. Step 2: Have that box react to keyboard input. Step 3: Replace black box with 1 static/unchanging picture. Step 4: Change the picture according to which direction the "box" is moving in. Make him face left/right/up/down etc. To do step 4, instead of doing like you are doing:
Try and break up where you process your game logic and where you draw things. This will help you make your games more complicated later on.
Note that loading a picture, then freeing it every frame is extremely inefficient, but it will make it much easier to do reach our final goal without learning about arrays/hashmaps. Alright, lets check our goal. Step ?: Play animations as the character moves. For your goal, you have to distinguish when you're currently holding the button down (to continue the animation) and when you first press the button down (to change and start a new animation) and when you release that button (to change back the standing animation). Step 5: Distinguish when the key was just pressed down. For this, we need to remember the last keyboard state. To do this, just make another variable to store it into before updating it. You're going to need to default the values of chars and charsLast before starting the loop, so that you don't get errors stating when you try charsLast := chars.
Since doing this code for all 4 arrow keys will seem repetitive, with the only thing changing between them being the placement of the not, making things harder to read. I suggest using functions.
Step 6: Use a variable to represent which picture in the animation we're on. Eg:
We then increment that variable (characterStateFrame) every frame. We should also reset it to 0 (the start of the animation) whenever we change animations (whenever characterState is changed). /mini tutorial |