Animatron/player — pull request #27 by shamansir (2012-07-09 18:11:36+00:00)
Title: Collisions: Linear collision test

Here comes the collision detection for linear movement (rotation/scaling will be taken into account in next PRs, it is much faster to include it). Here's the example, feel free to change options at the top:

anm.M[C.MOD_COLLISIONS].useSnaps = true; // default: false
anm.M[C.MOD_COLLISIONS].vectorSpan = 1; // default: 1
anm.M[C.MOD_COLLISIONS].predictSpan = 3; // default: 1; how far in time prediction goes

var blue_rect = b('blue-rect').rect([140, 25], [70, 70])
.trans([0, 3], [[120, 20], [40, 40]])
.fill('#009')
.stroke('#f00', 3)
//.rotate([0, 10], [0, Math.PI / 2]);
var red_rect = b('red-rect').rect([115, 90], [60, 60])
.fill('#f00');

blue_rect.v.track = true; // not required when useSnaps == false
blue_rect.modify(function(t) {
// COLLISION TEST HERE. notice that it is deferred
this.$.collides(red_rect.v, function() {
console.log(arguments); // called every time when collision predicted
});
});

return b()
.add(blue_rect)
.add(red_rect)
//.rotate([0, 10], [0, Math.PI]);

Vector data is stored, but currently not provided, because I need to prepare it before giving it to user.

The nice thing is when you check the collision for element, you see its predicted vector in debug mode!

Things to mention:

There are two modes of collision prediction:

* `useSnaps == false` (default): Predicted vector of movement is calculated using just the difference between previous and current state. It is ok for most of the time, but when your shape moves and stops occasionally, may be it is not so good.
* `useSnaps == true`: Tries to calculate the vector on the approximate movement through given time (`vectorSpan`). So if you'll set `vectorSpan` to `2`, it will take velocity vector from previous two seconds (approximately). It is required to set `track` property of such element to `true` to use it. It will not save state for every frame, it will save ~0, ~2, ~4, ~6 ... positions (will store only two last ones) and for the positions in time between 0 and 2 it will take the existing information (for 0.8 it will be vector 0 to 0.8), always shorter than 2sec, and for positions in between of "snaps" it will try to get approximate vector from the snaps it has: for 6.7 it will find the midpoint of 4.7 using saved 4 and 6 snaps and then get a 2sec-range vector between 4.7 and 6.7 to predict movement.