In Box2D, how to set the sleepTime of an object? - javascript

I'm working on a educational physics project and I've chosen Box2D as my main engine for a "Build your own rocket" like physics game.
Box2D looks very intuitive and the documentation seems pretty good IMMO, but I couldn't find how to set the sleeping time of a given body. Is it possible?
I've already tried the lazy approach:
var newB = new b2BodyDef();
newB.m_sleepTime = 12000;
Unfortunately, the newB still starts to sleep almost instantaneously after it gets into a rest position.

You can SetSleepingAllowed(bool) on an individual body, or set the entire world to not sleep when you create it. Unless you have a huge number of bodies in your simulation, I would just use one of these and keep the body awake all the time. You can also SetAwake(bool) on individual bodies if you know when you'll need them to be awake.

Related

How to make a character generator using sprite sheet and JavaScript

http://www.famitsu.com/freegame/tool/chibi/index1.html
I want to build a character generator exactly like this one. Someone suggested me that it'd be easy to use a canvas library, followed by low level JavaScript programming. Some said I don't need canvas and can do it easily with JavaScript. Since I've only learnt core JavaScript so far, hence I really don't have any knowledge or idea about this scene. So can you suggest me where and how to start this project of mine? And what are the required languages I should acquire first before jumping onto this project?
The components of an interactive, graphic application:
Something on which to draw (canvas)
Something to draw (graphics)
Looping drawing logic (animation loop and how to throttle it)
The game/application's functionality (game loop)
Interactivity (event listeners that can react to key presses, clicks, etc.)
Sound effects and music
These things are the basic building blocks of any interactive, graphic application.
JavaScript is a great language to use when starting out (or even beyond that) because the same concepts apply here as anywhere else, but you can save your code, and run it in your favorite browser!
Here's a Tetris example I've been working on lately in JavaScript that draws the board on an HTML5 canvas. It may seem a little complicated and overwhelming, but all the pieces are there that I've discussed (except for sound =/).
Just for reference, the tick function is my main animation loop. It runs as fast as the window will return animation frames, which is usually quicker than necessary. Once the tick function is called once, it will continue to run until explicitly stopped.
Tet.prototype.tick = function()
{
var _self = this; // needed for next step
// This line is what will make this function run repeatedly
this.requestId = requestAnimationFrame(function(){_self.tick()});
// Get some time information
this.tickNow = Date.now();
this.tickDelta = this.tickNow - this.tickThen;
// If it's been long enough, and it's time to draw a frame...
if (this.tickDelta > this.tickInterval)
{
this.tickThen = this.tickNow - (this.tickDelta % this.tickInterval);
// Run the game loop
this.doGameLoop();
// Draw the updated board
this.renderer.drawBoard(this.data, this.curPiece, this.curPieceGuide);
}
}
Game making can be intimidating at first, because it seems there are SO MANY pieces that need to be understood before you can accomplish what you see in your head, but if you take the concepts one-at-a-time, and start small, you'll be making crazy stuff in no time!

asynchronous / variable framerate in javascript game

This may be a stupid/previously answered question, but it is something that has been stumping me and my friends for a little while, and I have been unable to find a good answer.
Right now, i make all my JS Canvas games run in ticks. For example:
function tick(){
//calculate character position
//clear canvas
//draw sprites to canvas
if(gameOn == true)
t = setTimeout(tick(), timeout)
}
This works fine for CPU-cheep games on high-end systems, but when i try to draw a little more every tick, it starts to run in slow motion. So my question is, how can i keep the x,y position and hit-detection calculations going at full speed while allowing a variable framerate?
Side Note: I have tried to use the requestAnimationFrame API, but to be honest it was a little confusing (not all that many good tutorials on it) and, while it might speed up your processing, it doesn't entirely fix the problem.
Thanks guys -- any help is appreciated.
RequestAnimationFrame makes a big difference. It's probably the solution to your problem. There are two more things you could do: set up a second tick system which handles the model side of it, e.g. hit detection. A good example of this is how PhysiJS does it. It goes one step further, and uses a feature of some new browsers called a web worker. It allows you to utilise a second CPU core. John Resig has a good tutorial. But be warned, it's complicated, is not very well supported (and hence buggy, it tends to crash a lot).
Really, request animation frame is very simple, it's just a couple of lines which once you've set up you can forget about it. It shouldn't change any of your existing code. It is a bit of a challenge to understand what the code does but you can pretty much cut-and-replace your setTimeout code for the examples out there. If you ask me, setTimeout is just as complicated! They do virtually the same thing, except setTimeout has a delay time, whereas requestAnimationFrame doesn't - it just calls your function when it's ready, rather than after a set period of time.
You're not actually using the ticks. What's hapenning is that you are repeatedly calling tick() over and over and over again. You need to remove the () and just leave setTimeout(tick,timeout); Personally I like to use arguments.callee to explicitly state that a function calls itself (and thereby removing the dependency of knowing the function name).
With that being said, what I like to do when implementing a variable frame rate is to simplify the underlying engine as much as possible. For instance, to make a ball bounce against a wall, I check if the line from the ball's previous position to the next one hits the wall and, if so, when.
That being said you need to be careful because some browsers halt all JavaScript execution when a contaxt menu (or any other menu) is opened, so you could end up with a gap of several seconds or even minutes between two "frames". Personally I think frame-based timing is the way to go in most cases.
As Kolink mentioned. The setTimeout looks like a bug. Assuming it's only a typo and not actually a bug I'd say that it is unlikely that it's the animation itself (that is to say, DOM updates) that's really slowing down your code.
How much is a little more? I've animated hundreds of elements on screen at once with good results on IE7 in VMWare on a 1.2GHz Atom netbook (slowest browser I have on the slowest machine I have, the VMWare is because I use Linux).
In my experience, hit detection if not done properly causes the most slowdown when the number of elements you're animating increases. That's because a naive implementation is essentially exponential (it will try to do n^n compares). The way around this is to filter out the comparisons to avoid unnecessary comparisons.
One of the most common ways of doing this in game engines (regardless of language) is to segment your world map into a larger set of grids. Then you only do hit detection of items in the same grid (and adjacent grids if you want to be more accurate). This greatly reduces the number of comparisons you need to make especially if you have lots of characters.

Good JavaScript engine for animating via Sprite Sheets (not in canvas)

I've looked around a bit for a great JavaScript Sprite Sheet animator lib/engine but couldn't find any good ones so I thought I'd ask around =).
What I'm looking for in the engine is:
Animate an image in a non-canvas setting (ex: div via css or img
tags)
Control frame rate/animation speed
Flags to loop or to animate
once etc.
Are there any engines like this out there? If not I can always make my own but then again, I don't want to re-invent the wheel =].
I've used Spritely in the past and been successful. They give you a pretty healthy amount of control over the animation process. And besides, even if you don't find it useful, I'm sure you may find a good use for it sometime later down the road.

jQuery animate effect optimization

I am experimenting with jQuery and the animate() functionality. I don't believe the work is a final piece however I have problem that I can't seem to figure out on my own or by trolling search engines.
I've created some random animate block with a color array etc and everything is working as intended including the creation and deletion of the blocks (div's). My issue is within 2mins of running the page, Firefox 4 is already at more than a 500,000k according to my task manager. IE9 & Chrome have very little noticeable impact yet the processes still continue to increase.
Feel free to check out the link here: http://truimage.biz/wip300/project%202/
My best guess are the div's are being created at a greater speed than the 2000ms they are being removed however I was hoping an expert might either have a solution or could explain what I am doing wrong and some suggestions.
On another note, from the start of my typing this out till now the process is at 2,500,000k. Insane!m
It could be a lot of things other than just your script there. It could be a mem leak in one of the jQuery things you use, pretty hard to say.
Something you could try is this though:
Instead of creating new squares, use a "square pool". Let's say you create 20 squares and just keep re-using them instead of creating new ones.
You'd basically just have an array for the pool and take elements out from it when they are displayed, and put them back to it when the animation finishes.

Efficient realtime SVG entity management with javascript

[edit]sigh... the "spam protection" here isn't letting me post the links, so I guess it's URIs instead[/edit]
[edit2]ok, BROKEN forms of the URI that can get past the regexp...[/edit2]
I'll preface this by saying I'm totally new to SVG, and somewhat new to Javascript, having come from a background in low-level C. On a whim, though, I decided to try my hand at writing a realtime game using all these fun new web technologies.
I'm fully prepared for the answer to be "The web can't do that yet, sorry!" This may simply be too much data throughput for a browser.
So I have written the beginnings of an Asteroids clone. It is a thin SVG document, with the entire game being dynamically generated as SVG line/polygon entities from javascript. Much to my surprise, this actually worked. I was able to get mostly smooth animation from Firefox 3.5 (not tested on anything else).
original, as-needed allocation version
(javascript) http - public.codenazi.fastmail.fm/asteroids_dynamic.js
This does variations of this each time a rock it hit:
// on startup
svg_ns = 'http://www.w3.org/2000/svg';
container = svgdoc.getElementById('rocks');
// each time a rock breaks, times ~20
x = svgdoc.createElementNS(svg_ns, "polygon");
x.setAttribute(...various things...);
container.appendChild(x);
Unfortunately, it's not smooth enough. It lags all the time. There are jerks and breaks in the flow, even on my modern 3GHz box. Several friends I have shown it to also immediately complained of stuttering.
I have spent the last week or so reading up on how to optimize javascript, which helped slightly, but I suspect that the issue is all of the insertions/deletions I am doing to the DOM for pretty much every action in the game. I have considered various pre-allocation schemes, and don't really want some complicated memory manager if it's not actually going to help.
What did come up a lot in my research is discussions of "reflow" and "repaint". As I understand it, any insertion/deletion to the DOM will cause some sort of re-parse of the entire tree, which is slow. The common solution was to collect sub-nodes together first, and only do a single insert into the actual document. This model doesn't really work with a game like this, though.
As a test, I sort of combined the two ideas: pre-allocate when possible, and insert in groups when possible. So in this version, each asteroid is replaced with a SVG group, and the asteroid, it explosion effects, and its pop-up score are created all at once. This way, allocations and insertions only happen when asteroids are created (not destroyed). To keep these extra effects hidden until they are needed, I set the "display: hidden" attribute.
new, group-preallocated version: http - public.codenazi.fastmail.fm/asteroids_prealloc.svg
(javascript): http - public.codenazi.fastmail.fm/asteroids_prealloc.js
When the rocks are created, this happens instead:
g = svgdoc.createElementNS(svg_ns, "g");
// make the rock itself
rock = svgdoc.createElementNS(svg_ns, "polygon");
rock.setAttribute(...various things...);
g.appendChild(rock);
// make the destroy effect (repeated many times)
frag = svgdoc.createElementNS(svg_ns, "line");
frag.setAttribute(...various things...);
frag.style.display = 'none';
g.appendChild(frag);
// actually add it
container.appendChild(g);
// then, sometime later when a hit is detected
rock.style.display = 'none';
frag.style.display = 'block';
I think this DID make it a bit smoother! But... it also dropped the framerate significantly. I have to keep track of more elements at once, and some testing has shown that wrapping everything in another element makes the SVG render slower as well.
So my question is this: is this even possible? Can I actually get a reasonably smooth SVG animation like this out of firefox? Or is firefox inherently going to have stalls/stutters? If it is possible, is there some memory/element management technique that can allocate/insert SVG elements in a better way than I currently am?
I kind of suspect that the answer will be to just stick with the first, easier method with fewer elements and wait for the future when browsers are better... -sigh-
I haven't tried SVG animation (yet); but Canvas is surprisingly good at it; especially if you do layers.
In short, create a canvas object for each layer, and erase/redraw each one separately. You can also do quick blitting between an off-screen canvas an the displayed ones.
I know, in theory SVG should be much quicker; but as you've noticed, the DOM parsing kills you. with Canvas there's no need for that.
Okay, first things first:
Dude - that is the most awesome bit of SVG I have ever seen. Thank you for sharing this.
It ran perfectly smoothly on my system, until I destroyed a whole bunch of rocks at once. What if you replace the dynamic frag animation with a pre-made SVG animation? Does that improve performance?

Categories

Resources