praveen42

Martial Art Sim

Apr 29th, 2021 (edited)
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let c = document.getElementById("my-canvas");
  2. let ctx = c.getContext("2d");
  3.  
  4. let loadImage = (src, callback) => {
  5.   let img = document.createElement("img");
  6.   img.onload = () => callback(img);
  7.   img.src = src;
  8. };
  9.  
  10. let imagePath = (frameNumber, animation) => {
  11.   return "/images/" + animation + "/" + frameNumber + ".png";
  12. };
  13.  
  14. let frames = {
  15.   idle: [1, 2, 3, 4, 5, 6, 7, 8],
  16.   kick: [1, 2, 3, 4, 5, 6, 7],
  17.   punch: [1, 2, 3, 4, 5, 6, 7],
  18. };
  19.  
  20. let loadImages = (callback) => {
  21.   let images = { idle: [], kick: [], punch: [] };
  22.   let imagesToLoad = 0;
  23.  
  24.   ["idle", "kick", "punch"].forEach((animation) => {
  25.     let animationFrames = frames[animation];
  26.     imagesToLoad = imagesToLoad + animationFrames.length;
  27.  
  28.     animationFrames.forEach((frameNumber) => {
  29.       let path = imagePath(frameNumber, animation);
  30.  
  31.       loadImage(path, (image) => {
  32.         images[animation][frameNumber - 1] = image;
  33.         imagesToLoad = imagesToLoad - 1;
  34.  
  35.         if (imagesToLoad === 0) {
  36.           callback(images);
  37.         }
  38.       });
  39.     });
  40.   });
  41. };
  42.  
  43. let animate = (ctx, images, animation, callback) => {
  44.   images[animation].forEach((image, index) => {
  45.     setTimeout(() => {
  46.       ctx.clearRect(0, 0, 500, 500);
  47.       ctx.drawImage(image, 0, 0, 500, 500);
  48.     }, index * 100);
  49.   });
  50.  
  51.   setTimeout(callback, images[animation].length * 100);
  52. };
  53.  
  54. loadImages((images) => {
  55.   let queuedAnimations = [];
  56.  
  57.   let aux = () => {
  58.     let selectedAnimation;
  59.  
  60.     if (queuedAnimations.length === 0) {
  61.       selectedAnimation = "idle";
  62.     } else {
  63.       selectedAnimation = queuedAnimations.shift();
  64.     }
  65.  
  66.     animate(ctx, images, selectedAnimation, aux);
  67.   };
  68.  
  69.   aux();
  70.  
  71.   document.getElementById("kick").onclick = () => {
  72.     queuedAnimations.push("kick");
  73.   };
  74.  
  75.   document.getElementById("punch").onclick = () => {
  76.     queuedAnimations.push("punch");
  77.   };
  78.  
  79.   document.addEventListener("keyup", (event) => {
  80.     const key = event.key;
  81.  
  82.     if (key === "ArrowLeft") {
  83.       queuedAnimations.push("kick");
  84.     } else if (key === "ArrowRight") {
  85.       queuedAnimations.push("punch");
  86.     }
  87.   });
  88. });
  89.  
Add Comment
Please, Sign In to add comment