Simple 2D collision detection with Javascript.

Posted by DusX on 29 August 2014 | Comments

Tags: , ,

In a previous post, I embedded a video of a particle animation generated by a few generated wave forms, and a morphing rectangle. The particle would react everytime it came in contact with the rectangle. At the time of making the post I could not disclose how the collision detection was done, and it could have easily been done using the standard logic actors that have been available in Isadora for years, but it was not; it was created using the new Javascript actor.

The new Javascript actor takes advantage of the blazing speed of Googles V8 javascript engine and embeds this processing power in a easy to use way inside Isadora. It looks just like every other actor, but a quick double click opens up a world of possibilities.

So, getting right to it, the reason you are likely here, you want the code. Its pretty simple, and only checks the position of one point in respect to a quad (2D detection). Therefore it requires 6 inputs, the XY of the point, and the XY for two diagonally opposite points of the quad (this works because we are not rotating the quad and each corner is 90 degrees).

// requires 6 inputs.
// ins= HorzPos, VertPos, Horspos1, Vertpos1, Horspos3, Vertpos3
// requires 1 output. given as a boolean (true or false)
// note rect (is like CSS: top (top left is 1), right, bottom, left : 1,2,3,4)

function main()
{
var State;
var HorzPos = arguments[0];
var VertPos = arguments[1];
var Horspos1 = arguments[2]; // upper left of Rect
var Vertpos1 = arguments[3];
var Horspos3 = arguments[4]; // bottom right of Rect
var Vertpos3 = arguments[5];

if (((HorzPos > Horspos1) && (HorzPos < Horspos3)) &&
((VertPos > Vertpos1) && (VertPos < Vertpos3)))
{ State = true; }else{ State = false; } var out = [State]; return out; }

 

It outputs just one value, a boolean for the state of the collision.
You can see my first experiment with using this method of collision detection here.