Continue last post, the second and third arguments in the ctx.drawImage is the position of the cat image we want to crop. If spriteWidth times 0 and spriteHeight times 0, the image in the canvas is the first image of the “sprite sheet.png”.
So if the spriteWidth times 1 and spriteHeight times 0, it crop the second image of the first row. So if want to change another action, change the spriteHeight. And the spriteWidth is the animation of that action.
Now to animation the cat, create variables: gameFrame is 0, stagger is 0, and staggerFrame is 5. The gameFrame is variable to make the cat animation, stagger and staggerFrame is make the animation slower. In animate() function, write if-elif statement to check if stagger divide by staggerFrame is 0, so we draw the image. And create frameX is spriteWidth times the gameFrame divide by 4, and create frameY is spriteHeight times 0. Then replace second and third argument in the “ctx.drawImage” with framex, frame y. And after draw the image, added 1 to gameFrame and stagger.
After run the code, the cat is running on the canvas. You can see it below.
Now to make the cat animation with other actions, create variables; index is 0, playerState is run. Create a spriteAnimations list, it contain actions of the cat. And also create an object called animationStates, it contains the frame number of each action. Inside the animate(), make the index is return the index number of the playerState in the spriteAnimations list. Example if the playerStates is attack, it will return the index number of attack in the spriteAnimations, which is 1. In the frameX, change the gameFrame divide by 4 to gameFrame divide by the animationStates[index].frames. It will return frames number of that action, like if the index is 1, animationStates[1] is attack and it have 6 frames for attack action, so the gameFrame is divide by 6. And the frameY is spriteHeight times index. After you run the code, all cat action are animate on the screen. If the playerState is dash, it will do cat dash animation.
Next is make the dropdown to can choose action. Go to the “index.html” file, create a class called control, add “kat.png”, then create select have id animations and have 4 options, and also make a label for the dropdown.
Like you see above the dropdown is not in middle of the screen. So go to the “style.css” to style it.
This is how it look like after you run the code.
Final thing to do is make the dropdown work. Go back to the “script.js” file, create a variable called dropdown, it get element by id “animations”. And addEventListener to the dropdown, its event type is change. And make function(e), the playerState is e.target.value. That mean it will take the value is chose and the animaton of that action will running on the screen.
You can see how it work below.
No Responses