English subtitles

← Animation - HTML5 Game Development

Get Embed Code
7 Languages

Showing Revision 8 created 05/25/2016 by Udacity Robot.

  1. Lets take a look at the solution to this its a little bit tricky. Firstly, at
  2. the top of our file we declare two new variables, frameRate and frame. Now,
  3. frameRate represents how often we'd like to actually call the animate function.
  4. Frame is a variable that we're going to use to represent what the current frame
  5. in our flip book is. Since we already have our frames array available, the next
  6. step is to actually loop through our predefined assets, and load each of the
  7. defined images into the frames array. This follows the same 3 step process we
  8. saw before: create a new image, set its on load result, and then set its source.
  9. Once this is done we can actually call this setInterval function, which will
  10. call the animate function at the frameRate that we provided before. Now the
  11. animate function has a little bit of tricky logic inside of it. First off, we
  12. have our frame counter that we've defined. We use this to define what image out
  13. of the frames array we have to draw to the canvas, and of course, at our lovely
  14. position of 192 by 192. Once we've drawn the current frame we actually have to
  15. increment it, and that's where this little nice piece of math comes along. What
  16. we do is increment the frame counter and then modulo it by the frame's length.
  17. What will occur here is that if frame ever becomes longer than frame length, the
  18. modulo function will have it loop around back to 0 without us having to have all
  19. the other if statements involved. This is a nice little piece of math that you
  20. should put in your code. Your employer will be impressed by it. Now if you
  21. followed all the code, you should see something like this running around on the
  22. screen. If you'll notice, something of this doesn't exactly look right. You
  23. actually get each of the frames drawn over each other, creating this sort of
  24. halo effect. There's a reason for this. It's worth noting that the canvas
  25. doesn't actually clear itself each frame. Instead it allows you to just keep
  26. piling pixels on it as you go. In order to get rid of that ghosting effect, you
  27. have to put this line that we've conveniently left out of our previous function
  28. back in, and that is context.clearRect. What this will do is actually clear all
  29. of the pixels to some default value allowing us to draw back on top of it. So
  30. you won't get the previous images actually drawn on top of each other. The
  31. result is a nice, nifty walking robot running around on your screen, just like
  32. it should. The result with clearRect is this nice, fancy walking robot.