Game sprite animation - javascript

I am making a game and I want to animate my character(attacking, walking, etc) but I don't have an idea on how to do it. I know it is not for loop because if it is, the animation will play in an instant you won't be able to see it. I have downloaded a sample sprite sheet and I will test on it once I learn how to do it.

You can obtain sprites animation using CSS3's steps() function where supported. Or a plain javascript approach using timers (setTimeout, setInterval).
Here a simple examples of both: http://codepen.io/anon/pen/hCeuG
However for the JS part, it's better if you have a single game loop where you update your animation, that it's just an example. You can find a very deep explanation about javascript game loop here: http://nokarma.org/2011/02/02/javascript-game-development-the-game-loop/index.html

there are making JS based gaming libraries available that exists for the sole purpose of making games easier. you should be using one of them.
I have worked on some of them and I like CreateJS with extensive support of sounds and spritesheets.
in fact you can create spritesheets on fly using animations

You can use Free sprites or try to make it with Photoshop ( if you are pro ! ) or Sprite Maker ( for Basic users ! )
for 3D Models you can use

I was also in such situation.
CreateJS was very much helpful for me.
This library has avery good documentation on handling sprite-sheet and bitmap animation.
EaselJS has examples with source code to show how to use the sprite sheet in your game.
Another blog which was helpful for sprite sheet manipulation was by David Rousset: HTML5 Gaming: animating sprites in Canvas with EaselJS
I think these could be helpful for you

Related

Full width video background: A non-HTML5, purely jQuery solution...maybe

Long time Stack Overflow creeper. This community has come up with some incredibly elegant solutions to rather perplexing questions.
I'm more of a CSS3 or PHP kinda guy when it comes to handling dynamically displayed content. Ideally someone with a solid knowledge base of jQuery and/or Javascript would be able to answer this one best. Here is the idea, along with the thought process behind it:
Create a Full Screen (width:100%; height:auto; background:cover;) Video background. But instead of going about using HTML5's video tag, a flash fallback, iFrame, or even .GIF, create a series of images, much like the animation render output of say Cinema4D, that if put together in sequential order create a seamless pseudo-video experience.
In Before "THAT's JUST A .GIF, YOU'RE AN IDIOT" Guy.
I believe jQuery/Javascript could solve this. Would it or would it not be possible to write a script that essentially recognizes (or even adds) the div class of an image, then sets that image to display for say .0334ms (29.7 frame rate) then sets this image back in z space while at the same time firing in the next image within the sequential class order to display for another .0336ms; and so on and so forth until all of the images (or "frames") play out seamlessly fluid, so the user would assume he/she is actually seeing a video. Not a knowing it's actually a .GIF on steroids.
Here's a more verbose way of explaining the intended result:
You have a 1 second super awesome 1080p video clip (video format doesn't matter for helping to answer this question, just assume its lossless and really pretty k?). It's recorded at 29.97 frames per second. Break each frame into it's own massive image file, leaving you with essentially 30 images. 24 frames a second would mean you'd have 24 images, 60 frames per second would mean you'd have 60 images, etc., etc., excedera.
If you have ever used Cinema4D, the output I am looking to recreate is reflexive to that of an animation render, where you are left with a .TIFF per frame, placed side by side so that when uploaded into Photoshop or viewed in Quicktime you get a "slideshow" of images displaying so fast it look likes a video.
HTML would look something like this:
<div id="incredible-video">
<div class="image-1">
<img source=url('../movie/scene-one.tiff');/>
</div>
<div class="image-2">
<img source=url('../movie/scene-two.tiff');/>
</div>
<div class="image-3">
<img source=url('../movie/scene-three.tiff');/>
</div>
<div class="image-4">
<img source=url('../movie/scene-four.tiff');/>
</div>
<div class="image-5">
<img source=url('../movie/scene-five.tiff');/>
</div>
....etc.....
....etc.....
....etc.....
</div>
jQuery/Javascript could handle appending the sequential image classes instead of writting it all out by hand for each "frame".
CSS would look like:
#incredible-video img {
position:absolute;
width:100%;
height:auto;
background:cover;
}
But what would the jQuery/Javascript need to be to pull the off/can it be done? It would need to happen right after window load, and run on an infinite loop. Ofcourse audio is not happening in this example, but say we don't need it. Say we just want our End User to have a visually appealing page, with a minimal design implemented in the UI.
I love video animation, and really love sites built with Full Screen Backgrounds. But a site out with this visual setup and keeping it responsive is proving to strenuous a challenge. HTML5 will only get you so far, and makes mobile compatibility null and void (data usage protection). .GIF files are MASSIVE compared to calling in a .mp4, .Webm, or .OGG so that option is out.
I've actually recently played around with Adobe Edge Animate. Using the Edge Hero .js library I was able to reproduce a similar project to this: http://www.edgehero.com/tutorials/starwars-crawl-tutorial
I found it worked on ALL devices. Very cool. Made me think that maybe it's possibly to use this program or hit jQuery/Javascript directly to achieve the desired effect.
Thanks for taking a look at this one guys.
-Cheers,
Branden Dane
I found a viable solution to what I was looking to do. It's actually rather interesting. The answer it's introduces many interesting ideas on how we can display any kind of content dynamically on a site, in an app, or even a a full fledged software application.
The answer came about while diving hard into WebGl, canvas animation (both 2d and 3d), 2D video games techniques, and 3D video game techniques. Instead of looking for that "perfect" workflow, if you are someone interested in creating visually effective design and really seeing what the bleeding edge can do for your thoughts on development, skip the GUI's. Ignore the ads with software promising to make things doable in 5 min. It's not. However we are getting there. 3 major events we have to look forward too in just a few months are
1.) the universal agreement to implment WebGL natively in Opera, Chrome and Firefox (ofcourse), Safari will move to ship with webGL enabled, compered to the user having to enable it manually, and even IE is going to try and give her a go (in IE 12).
2.) Unity 3D, an industry standard in game development, has announced that next month it will release version 5, and with it a complete, intuitive workflow from start to exporting in Javascript (not JSON actual JavaScript). The Three.JS library more specifically as it is one of the most popular of the seemingly endless games engines out today.
How does this answer my initial question?:
Though WebGL has been around for about 3 years now, we are only now starting to see it shine. It's far more than a simple video game engine. With ThreeJS We have a full working JavaScript library, capable of rendering in WebGL, to the Canvas, or EVEN with a few CSS3 magic. Can't use your great movie as a mobile background? It ruining the overall UI? Cheer up. ThreeJS can working with both 2D and 3D javascript draw function, though not at the same time. Hover other libraries exist that allow you to bypass this rule.
AND DRUM ROLL. It is, or can be very easily made in a responsive or adaptive way.
The answer to my question came from looking at custom preloaders. Realizing I can create incredible looping animations in AE, and export them as GIFs offered the quality I wanted, but not control, no optimization, now sound. However, PNG Sequences CAN be exported. Then the epiphany hit. Before I just say what I am using to solve my problem, I'd like to leave a list of material anyone looking to move beyond easy development and challenge limits can use as a reference guide. This will be in order with what I began to where I am now. I hope it helps someone. The time to find it all out would be very much worth it.
1.) WebGL-Three.JS
WebGL opened my eyes to a new world. It's a technology quickly evolving and is here to stay. In a nutshell, all live applications you create now have access to more than just a CPU, but also the Graphics card as well. With GPU's getting more and more powerful, and not so unreasonably priced, the possibilities are endless. The idea we could be playing Crysis 3 "in-browser" without the need of a 3rd party client is no fiction. It's the future. Apply that to websites. Mind blown.
2.) First Cinema4D, then start working around with Verold.com & PlayCanvas.com
C4D is just my personal favorite because if it's easy integration with AE. You will find that with exporting your 3D models, Textures, Mesh's, anything to Three.JS (or any game engine period) that it is Blender that is the most widely supported. As of writing this, their are 2 separate C4D workflows to ThreeJS. Both are tedious, not always going to work, and actually just unnecessary. PlayCanvas was also a bit of a let down. Verold, however is an EXCELLENT browser based 3D editor in which you can import a variety of files (even FBX with Baked animations!) and when you are satisfied you can export into a standalone client or an iframe. The standalone client is superb. It is a bit glitchy, so have patience. You shouldn't get comfortable with it any way. Go back to your roots.
3.) iPhone app development, Android app dev (to an impressive extent), Web Sites, Web Apps, and more all function in a way that an application need only be made using JavaScript, HTML/5 and CSS/3. Once this is understood, and the truth hits you as to how much control you may not have known you had, then the day becomes good indeed. Learn the code. With a million untested and horrible "GUI's" out there that claim to do what you want, avoid the useless search. Learn the code. You can never go wrong at that point.
4.)What code do I need to learn?
JavaScript is the most essential. More on that in a moment. Seriously dive into creating apps of any kind with ThreeJS. Mr. Doob (co-creator of the library) has an EXCELLENT, well-documented website with tons of examples, tuts, and source code for you to dive into. Chrome Experiments is your next awesome option to see how people are really taking this kind of development to a new level. In the process of learning ThreeJS, you'll become more proficient with JavaScript. You will also start to play with things you maybe never had to, like JSON, or XML files for packaging data. You'll also learn how simple it is to implement Three.JS as a WebGL render, or even fallbacks to Canvas and even CSS3D if and when possible.
Before going on, I will make a caveat. I believe that once Unity 3D drops ThreeJS fro pro and free users, we will see much much more 3D in the web. In that case, it can't hurt to Download the software and play around a bit. It also serves an an excellent visual editor. There are exporters from Unity 3D to ThreeJS, but again they are still pre alpha stage.
2D or not 2D. that is the question
After getting a little dirty with 3D I moved into drawing in the 2D realm using the canvas. Flash still seems like a viable tool, but again, it's all about the code. Learn how to do it and you may find Flash is actually costing you time. I found 2D more difficult than 3D because the nature of 2D has yet to radically change, at least in my lifetime. You'll need to start learning Spritesheet creation tutorials. Nothing incredible hard if you know where to look. Use A photoshop, or an equivalent application. Create as many "movement" frames that if were put together in a GIF would be enough to seamlessly loop the sprite. OR render a master image out and cut around the elements naturally distinct pats. Ex: You want to make the guy you have standing on a street corner you created, stays. Cut that character up in as many separate PNG files as you believe you need. The second method is all about using the same sprite sheet we brought in the first try. The first scenario meant writing CSS selector and have javascript written for the regular user would become increasingly difficult.
First solution: Using CSS and Javascript to plot "frames" meticulously put together in the sprite sheet. This really can become a pain if not done correctly all the way through.
Second solution: We lose the frame by frame effect if we need it, but our overall 2D animations will look incredible. Also, building in this way creates more efficient games when implementing physics engines and setting up collision detectors. We will still use the same sprite sheet, however we only need to choose the frames we really actually need. The idea is to use dynamic tweening between frames that are called together via Javascript. In the end you have a fully animated Sprite, but could have done so with just one frame. Ex: You have a Stickman you want to show walking in a straight line. Solution one would jump frame by frame, creating a mild chop, to illustrate an animated walk. In solution 2, we take the Stick man and chop his dynamic bits apart so we can call them through JavaScript, then build our sprite from JavaScript directly. To create the walking effect, we cut apart stickmans legs and have those separate in the sprite sheet from the rest of his body (unless you need to animate another body part as well). We map out where the coordinates are for each piece of stickman. Free software like DarkFunctionEditor is one of many programs that will instantly take care of generating for you a reliable sprite sheet, printing out the coordinates of your sprite sheet after you bake it. With this knowledge, head into JavaScript and call in your variables that you wish to associate to the pieces of Stick Man and their corresponding coordinates. Then use Javascript to "build" all the pieces together. The walking animation is accomplished by the Tween we talked about earlier. Each leg essentially runs on a beautifully fluid path you set in JavaScript. No chop. Very easy to customize and control. If you want to make it even easier for yourself, try using one of the many libraries for Sprite animation. My favorite at the moment being CreateJS.
If you are looking to include collision detection or create particle systems then you will need a physics engine. For 2D I am torn between 2 at the moment. Right now I would put PhysicsJS over KineticJS. Both are fantastic. I believe PhysicsJS integrates with CaccoonJS and other mobile scripts easier.
My last words of advice are=, after reading this, understand you will be working will JavaScript. You will have a bit of jQuery to make it easy, but you will encounter things that are difficult on the way. My HUGE recommendation is to move into learning how to build using NodeJS. It's an Asynchronous Javascript Server-side and client-side development space. The documentation is wonderful. Your first stop should be learing about npm, and bower. Then understand how to effectively implement Grunt into the workflow. Try out NodeJS assets like Yeoman to give you "boilerplate" Node setups from which to start with. After you start understanding NodeJS mechanics and feel comfortable with setting up your initial package.json, you'll find that all this JavaScript will almost feel like it's writing itself after a certain point.
And that's all you need to know to get into 2D and 3D design and development. My initial question could have been answered using say a 3D rendered fullscreen. However my final conclusion came in a different method entirely.
After learning about 2D sprites and framing, then noticing the encoding process of gifs. I had the idea to try and create PNG Sprite Animations. Not PNG Gifs, per say. But rather creating a 2D scene and using a PNG sequence that I would then animate via JavaScript. I found a few great libraries on Github, both for my idea and cool ideas for GIF manipulation.
My final choices was with the Github Repo "jquery.animateSprite" Instead of mulling through sprite sheets, you take your individual PNG's and this library gives you an incredible amount of control in how you can store variables for later use, but also the animations you can pull off in general. For a full screen, responsive background that works on any device (and can even be animated to sound....) I'd recommend this technique. It works much like a flip book animation works, except much much more effectively.
I hope this helps someone along the way. If you have a question on anything I have mentioned here, or know of an area that needs further detail, then by all means please let me know.
-Cheers

Uses for canvas | Practical examples

I'm trying to understand what people use canvas for?
I see it on job postings I read about it in Definitive JavaScript, but I don't quite get what it is used for.
I understand that you can draw 2d or 3d ( usually 2d ) objects but why no just use Gimp or Photoshop and upload the image.
Is it so you can create dynamic images based on say...user-specific data?
What is a practical example or perhaps a link to a professional implementation of canvas ( Definite JavaScript show basis stuff like drawing circles ).
MDN Tutorial
I have used a canvas to draw a graph, and it falls back to requesting a PHP-generated image if the browser doesn't support <canvas>. It's always a good idea to delegate processing from the server to the client, as this places less load on the server. In other words, instead of the server going "here's the stuff", it's more like "here's the data and the instructions to show it".
Another use I've seen is to highlight areas of an imagemap when moused over.
<canvas> is central in HTML5 game development, since it is used to draw the entire game viewport. Without it, there is no game.
Is it so you can create dynamic images based on say...user-specific data?
Yes
We used <canvas> to build interactive design editor for apparel in our e-commerce store — http://printio.ru/tees/new
The kind of interactivity we provide was only possible with Flash until recently.
Even on back end, we use Node.js and <canvas>-based image processing+generation to take data from online editor and create designs that are later used in store. These canvas-generated designs are eventually printed out on tshirts, mugs, caps, bags, and so on.
I think that's a pretty practical example :)
This is all done via Fabric.js canvas library (developed by us as well).
<canvas> is used for better Performance. <canvas> is much more faster and dynamic than jpeg or anything else. Example: http://www.profistart.com/internetseiten.html here was <canvas> used for Background.

game performance of html5 canvas and pure Javascript/GWT

I want to write an animated game which needs a lot of animations running all the time, something like rolling the cards/images in slot machine. I am wondering if I should mainly use just pure GWT/Javascript to run the animation, or use HTML5 Canvas or HTML5 animation to achieve this.
I know I might be able to make more fancy animated motion or graphics if I use HTML5 canvas, but I also cares about the performance more because there are several "animations" running in the same time just like rolling so many images in 5 columns slot machine. In this case, I think performance is most important.
I heard that drawing things in Canvas is really expensive. So I am not sure if I keep rolling images in Canvas is expensive as well.
What do you think which technique I should use to write a game like slot machine? HTML5-Canvas, pure JS/GWT-animation, or HTML5-animation?
I need to use some audio for the games, but I am pretty new to this, I do not know what libraries or technique I can use for audio. Please give me some advice.
Thanks.
if you have a lot of graphical animations, Canvas 2D will be a good choice. If you are dealing with vector shapes, simple animations SVG might be an option. I would not go for GWT as the abstraction layer of Java might hinder your ability to use full power of HTML/CSS/JS.
Ensure you use a basic game library if you choose plain JS and Canvas. I used jawsjs which is ok for simple games. See and observe the performance of below game which is based on Canvas 2D if you need a reference. Let me know if you need the code of it as a reference.
http://99challenge.com/_index.html
On audio, there are few challenges. Firefox behaves different to all other browsers, and has quite instable audio support. You might need to look for Flash support in getting audio to work properly on FF.

How do I draw my Box2D world using HTML5 Canvas instead of Debug Draw?

I know HTML5 canvas fairly well, I know the basics and animation using loops etc.
Demo I'm working with: (click to make shapes) http://henry.brown.name/experiments/box2d/example-canvas.html
What I'm not very familiar with is Box2D. I'm using the Box2DWeb port, I heard it was newer than Box2D-js, I'm not sure which is best.
I know how to initialize the 'world' and I can place objects in the world. I then use Step to animate the world - however to display it on the screen so far I've only been able to get it working with debug draw as it basically does everything for you.
Instead of using debug draw I'd like to use canvas to draw, for example a car instead of just a square. How do I attach the physics of a square to the image of a car? I just can't get my head around integrating canvas with Box2D.
Any tips will be massively appreciated!
Thanks
I spent the last few days trying the same thing.
I found Jonny Strömberg's tutorial, which is not super detailled but by analyzing the code I found how he retrieves the body's position:
var b = world.GetBodyList()
GetBodyList() seems to be an iterative Array, so the next body is accessible through b.m_next.
You can then use
b.GetPosition().x
b.GetPosition().y
b.GetAngle()
to retrieve the body's coordinates.
EDIT: this code is for the Box2dweb library, which I found better documented than Box2djs
If you aren't familiar with Box2D you should check out the documentation at http://www.kyucon.com/doc/box2d/. This should tell you all of the properties you need. To my knowledge the standard way of using Box2D is to attach an image with userData. See this example tutorial for image and Canvas image usage.
http://www.jeremyhubble.com/box2d.html
I had the same question.
here is the documentation of it.
You could use calls like GetBodyList() , GetAngle()and members like m_position to get all that you need to paint whatever using whatever library you want to use on a canvas.

How to make a rotating object (sphere, box, etc.) using only the canvas

I'd like to make a rotating object (sphere, box, etc.) using only the canvas. But I can't find a tutorial. Help If you saw somewhere or explain how to do it.
Like this example, only without any effects
Hope you like math. 3D effects can always be achieved on a 2D plane if you are willing to write some code.
Some resources that will probably help:
An Intro to Computer Graphics
and for help with the math,
A Book on Linear Algebra
Ah well it's pretty simple in theory. One way is to just set up a timer and then when it fires, clear the canvas and redraw your sphere, box whatever. To make it faster you can cover over a region of the canvas instead of the whole thing. Also you can get png sprites and move them about on the canvas.
I got into this stuff by trying out the pyjamas canvas wrapper, which means you can code in python and then compile it into js, which to me is a lot friendlier.
http://pyjs.org/examples/gwtcanvas/output/GWTCanvasDemo.html
NB the demo is slightly borken but the example code does compile and run perfectly well if you do a git pull.

Categories

Resources