Sprite.hitTestObject in ivankjs

update : this code will work correctly if the sprite contains only one single element
What is ivankjs ?
as the site say IvanK Lib is JavaScript 2D graphics library inspired by Flash.check out the documentation here and the demos here
Extending the librairy
As we know in flash we have the hitTestObject and the hitTestPoint for collusion detection but in ivankjs we have only the hitTestPoint wich does not do the trick some cases . fortunately we can extend the librairy.
Here’s a simple project to explain how :
<!--<script type="text/javascript" src="js/ivank.js"></script> --> <!-- Online Version --><script type="text/javascript" src="http://lib.ivank.net/ivank.js"></script><script type="text/javascript">// <![CDATA[
//class ball
function Ball( n )
{
Sprite.apply(this);
this.buttonMode = true;
this.name = n;
this.bg = null;
var bitmapData = new BitmapData( "images/ball.png",1 );
this.bg = new Bitmap( bitmapData );
this.addChild( this.bg );
}
// Ball extends Sprite
Ball.prototype = new Sprite();
// adding a util function to the Sprite Class
Sprite.prototype.isEqualTo = function(o){
for(var p in this){
if(o.hasOwnProperty(p)){
if(this[p] !== o[p]){
return false;
}
}
}
for(var p in o){
if(o.hasOwnProperty(p)){
if(this[p] !== o[p]){
return false;
}
}
}
return true;
}
// extending the librairy and adding the hitTestObject
Sprite.prototype.hitTestObject = function(o){
if(this.isEqualTo(o)) return;
var bounds = {x:this.x,y:this.x,width:this.GetWidth(),height:this.GetHeight()};
//console.log(bounds);
bounds.right = bounds.x + this.GetWidth();
bounds.bottom = bounds.y + this.GetHeight();
var compare = {x:o.x,y:o.x,width:o.GetWidth(),o:this.GetHeight()};
compare.right = compare.x + o.GetWidth();
compare.bottom = compare.y + o.GetHeight();
return (!(compare.right < bounds.x || compare.x > bounds.right ||
compare.bottom < bounds.y ||compare.y > bounds.bottom));
}
var stage;
var dragged = null;
var itemHolder = [];
function init() {
var stage = new Stage("c");
for (var i = 0; i < 2; i++) {
var s = new Ball( i );
stage.addChild( s );
s.x = Math.random()*800;
s.y = Math.random()*500;
s.addEventListener(MouseEvent.MOUSE_DOWN, onButtonDown);
s.addEventListener(MouseEvent.MOUSE_UP, onButtonUp);
itemHolder.push( s );
}
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMM );
}
function onButtonDown(e){dragged = e.target;}
function onButtonUp(e){dragged = null;}
function onMM (e)
{
if(dragged == null) return;
dragged.x = e.target.mouseX - dragged.mouseX;
dragged.y = e.target.mouseY - dragged.mouseY;
dragged.hitTestObject(dragged);
for (var i = 0; i < itemHolder.length; i++) { if(dragged.hitTestObject( itemHolder[i] ) === true) { //console.log("hitted"); itemHolder[i].x += 150; itemHolder[i].y += 150; } } }
// ]]></script><canvas id="c" width="860" height="500"></canvas>
this video show the final result :

