Animation theory (natural animations) - javascript

I want, for example: to animate how a bird is flying through the sky, i am not talking about the animation of the wings, but how to animate an object random over a canvas.
I use to animate those kind of objects with a lot of randomisation, for example: move [object] from a to b (random distance, random speed, random x, random y, etc.).
But is that really the best way to do it? or is there any algorithm theory available on how to achieve the most natural behaviour.
The animation can be a bird, but it could also be dust, or flying sand)
(I hope my question is clear enough)

In fact, a bird is rarely on its own in the sky, maybe you could have a look at flocking behavior of boids.
They basically lie on 3 rules known as
separation: steer to avoid crowding local flockmates alignment:
steer towards the average heading of local flockmates cohesion:
steer to move toward the average position (center of mass) of local
flockmate
This said you can imagine it is a bit different from sand and dust movement calculation, because these are actual physics problem (mostly fluid mechanics navier stokes)
But I'm pretty sure if you don't actually want to be accurate (navier stokes aren't accurate) you could hack some of boids rules to move particles.

Answer extracted from this post
Lévy flights or brownian motion should work. These are random walks
where at each time step the insect moves a random direction and
distance. They differ in what distribution the random variables are
sampled from.
The motion of hunting sharks can be modeled as brownian motion when
prey is plentiful and lévy flight when prey is scarce.
Depending on what you use it for, you might want to restrict their
motion (to keep them near a specific part of a level) or limit the
acceleration (to make them appear to have have more inertia).

Related

Why has my quadtree made no improvement to performance?

I have a boids flocking simulation setup. It originally worked by having every boid loop through every boid so that they all constantly know where each other are at in order to tell if they are close or far away, but then I switched to a quadtree design so that boids only have to loop through boids that are actually nearby. However, it has made virtually no improvement to the simulation's FPS. It's as if I'm still looping through every single boid.
Is there some mistake in my implementation? Repo is here, relevant code is mostly in main.js, quadtree.js, and boid.js. LIve site is here
The reason why you are not seeing obvious performance gains from the Quadtree is because of the nature of your simulation. Currently, the default separation causes a large number of boids to "converge" to the same position.
Lots of objects in the same position is going to negate possible speedups due to spatial partitioning. If all the objects are in the same or near position, boids in the area a forced to check against all other boids in the area.
You can demonstrate to yourself that your Quadtree is working by watching or profiling your application with its default settings. Now turn separation up to maximum. You will see visually, or through profiling, that as the boids spread out more evenly, the FPS increases significantly. This is because the Quadtree can now prevent computations thanks to its spatial partitioning.
With default low separation:
With maximum separation:
You can see how performance is increased in the second image. Also note, that the conjecture by another commentor that it is the construction of the Quadtree (insert) that is taking up all the time is wrong.
While in some applications you may be able to update a Quadtree as things move around, since in this simulation every constituent moves every frame, reconstructing the Quadtree from scratch is less work, then taking every object out and reinserting it into its new position.
The advice to skip square-rooting and just use the distance-squared is good though as this will get you a bit more performance.

How to make boids pursue a movable character in a 2d game

I was wondering what would be the simplest way to make my group of boids pursue my character in a top down 2d game with a path finding algorithm?
I'm thinking I'd have to first find a path to the player with the path finding, get the desired vector and then subtract that from the velocity to get the steering value.
I found "Pursuit and Evasion steering behaviors" on Craig Reynolds' website but I'm not sure if I'm heading in the right direction.
Note that there is a little more detail in a 1999 GDC paper. There are also many open source implementations, such as this (in retrospect, surprisingly complicated) one in OpenSteer.
An agent’s seek behavior simply assumes a desired velocity toward a static target, and defines a “steering force” which is the error/difference between that and its current velocity.
So a pursue behavior requires only to estimate a current target location. A rough approximation is usually good enough, since it is discarded after this animation frame / simulation step. Typically steering behaviors use constant velocity predictions, simply multiplying the current velocity by some time interval. A helpful estimate for that interval is the distance to the quarry agent, divided by our current speed.
How this interacts with (a) the pursuers being a flock, and (b) a simulation based on path finding, would depend on specific details of your game. Probably you want to blend a small pursuit “force” with the flocking behavior so it does not interfere with the nature of the flock.

rope simulation html5

I'm trying to simulate a rope physically correct on a website.
Having searched the web, my conclusion is that I need a physics engine like box2d?
If I have understood it right the solution is to split up an object into small segments and then to join and animate these all together. In addition, I want to combine the physics with the browser. What that means is: when I'm scrolling the website fast down, the rope has to react in a physically correct manner.
is this possible?
You don't need a library at all.
You can happily do this with object, component or procedural code, and an understanding of basic mechanical physics and some 2D geometry (basic calculus might help).
Doing it in an optimized fashion would require more work.
Doing it in a modular and reusable fashion would require some upfront engineering.
But making a rope, and making the rope behave normally is quite straightforward.
A 2D rope would be a series of line-segments or "bones".
Each bone can bend around its joints.
You can apply gravity or whatever other forces you would like to each bone.
Each bone has constraints (the other bones it's attached to, above and below).
So as you update the "rope", you update each bone, based on the constraints which came before and after.
You can create an anchor point -- pinning the top of the rope to the wall, so that regardless of how the other bones move, the top-most bone will pivot around its top joint, but will not move anywhere.
To apply physics to the middle of the hanging rope (like pulling it by the middle, and then letting go), you would use Inverse Kinematics to solve how that force against one or two joints affected each of the other attached (and constrained) joints.
Think of it less like a snake, and more like a bike chain.
The shorter each "link" in the chain, the more fluid the rope will seem, but the longer it will take to process.
The longer each "link" in the chain, the faster you can compute the changes, but the more rigid and blocky it seems as it bends.
Look up "Verlet Integration", "Kinematics" ("Forward"/"Inverse") and have a half-decent grasp of the math behind rotation and moving an object along 2D vectors...
With a little bit of mass in there, if you want to get fancy with the whip-like stuff, rather than just making waves.
The rest is just loops.
See the following for a basic example:
http://gamedev.tutsplus.com/tutorials/implementation/simulate-fabric-and-ragdolls-with-simple-verlet-integration/
And have fun.

HTML5 Canvas Collision Detection "globalCompositeOperation" performance

Morning,
Over the past few months I have been tinkering with the HTML5 Canvas API and have had quite a lot of fun doing so.
I've gradually created a number of small games purely for teaching myself the do's and don'ts of game development. I am at a point where I am able to carry out basic collision detection, i.e. collisions between circles and platforms (fairly simple for most out there but it felt like quite an achievement when you first get it working, and even better when you understand what is actually going on). I know pixel collision detection is not for every game purely because in many scenarios you can achieve good enough results using the methods discussed above and this method is obviously quite expensive on resources.
But I just had a brainwave (It is more than likely somebody else has thought of this and I am way down the field but I've googled it and found nothing)....so here goes....
Would it possible to use/harness the "globalCompositeOperation" feature of canvas. My initial thoughts were to set its method to "xor" and then check the all pixels on the canvas for transparency, if a pixel is found there must be a collision. Right? Obviously at this point you need to work out which objects the pixel in question is occupied by and how to react but you would have to do this for other other techniques.
Saying that is the canvas already doing this collision detection behind the scenes in order to work out when shapes are overlapping? Would it be possible to extend upon this?
Any ideas?
Gary
The canvas doesn't do this automatically (probably b/c it is still in its infancy). easeljs takes this approach for mouse enter/leave events, and it is extremely inefficient. I am using an algorithmic approach to determining bounds. I then use that to see if the mouse is inside or outside of the shape. In theory, to implement hit detection this way, all you have to do is take all the points of both shapes, and see if they are ever in the other shape. If you want to see some of my code, just let me know
However, I will say that, although your way is very inefficient, it is globally applicable to any shape.
I made a demo on codepen which does the collision detection using an off screen canvas with globalCompositeOperation set to xor as you mentioned. The code is short and simple, and should have OK performance with smallish "collision canvases".
http://codepen.io/sakri/pen/nIiBq
if you are using a Xor mode fullscreen ,the second step is to getImageData of the screen, which is a high cost step, and next step is to find out which objects were involved in the collision.
No need to benchmark : it will be too slow.
I'd suggest rather you use the 'classical' bounding box test, then a test on the inner BBOxes of objects, and only after you'd go for pixels, locally.
By inner bounding box, i mean a rectangle for which you're sure to be completely inside your object, the reddish part in this example :
So use this mixed strategy :
- do a test on the bounding boxes of your objects.
- if there's a collision in between 2 BBoxes, perform an inner bounding box test : we are sure there's a collision if the sprite's inner bboxes overlaps.
- then you keep the pixel-perfect test only for the really problematic cases, and you need only to draw both sprites on a temporary canvas that has the size of the bigger sprite. You'll be able to perform a much much faster getImageData. At this step, you know which objects are involved in the collision.
Notice that you can draw the sprites with a scale, on a smaller canvas, to get faster getImageData at the cost of a lower resolution.
Be sure to disable smoothing, and i think that already a 8X8 canvas should be enough (it depends on average sprite speed in fact. If your sprites are slow, increase the resolution).
That way the data is 8 X 8 X 4 = 256 bytes big and you can keep a good frame-rate.
Rq also that, when deciding how you compute the inner BBox, you can allow a given number of empty pixels to get into that inner BBox, trading accuracy for speed.

Most efficient way to implement mouse smoothing

I'm finishing up a drawing application that uses OpenGL ES 2.0 (WebGL) and JS. Things work pretty well unless I draw with very quick movements. See the image below:
This loop was drawn with a smooth motion, but because JS was only able to get mouse readings at specific locations, the result is faceted. This happens to a certain degree in Photoshop if you have mouse smoothing turned off, though obviously much less because PS has the ability to poll at a much higher rate.
So, I would like to implement some mouse smoothing, but I'm concerned about making sure it's very efficient so that it doesn't bog down the actual pixel drawing operations. I was originally thinking about using the mouse locations that JS is able to grab to generate splines and interpolate between readings to give a smoother result. I'm not sure if this is the best approach, though. If it is, how do I make sure I sample the correct locations on the intermediate spline? Most of the spline equations I've found don't have uniformly-distributed values for t = [0, 1].
Any help/guidance/advice would be very appreciated. Thanks!
Catmull-Rom might be a good one to try, if you haven't already.
http://www.mvps.org/directx/articles/catmull/
I'd pick a minimum segment length and divide up segments that are over that into 1+segmentLength/minSegmentLength sub-segments.

Categories