I am pretty new to both CANVAS and Kineticjs but I feel what I am attemping should be much easier then I am making it out to be. Basically this is what I have so far:
<
Yes, since KineticJS doesn't have collision testing you must do your own.
Here is a collision test between any 2 kineticJS rectangles:
function theyAreColliding(rect1, rect2) {
return !(rect2.getX() > rect1.getX()+rect1.getWidth() ||
rect2.getX()+rect2.getWidth() < rect1.getX() ||
rect2.getY() > rect1.getY()+rect1.getHeight() ||
rect2.getY()+rect2.getHeight() < rect1.getY());
}
And here is how you would call the collision test between the box and obstacle:
if( theyAreColliding(box,obstacle){
// obstacle is blocking box
alert("You are being blocked!");
}
And here is how you would call the collision test between the box and the goal:
if( theyAreColliding(box,target){
// box touched the goal
alert("Goal!");
}
To stop the box from dragging right through the obstacle, you must give box a custom drag function like this:
dragBoundFunc: function(pos){
if(theyAreColliding(box,obstacle){
// box is touching obstacle
// don't let box move down
return({ x:pos.x, y:obstacle.getY()-1 });
} else{
// box is not touching obstacle
// let it move ahead
return({ x:pos.x, y:pos.y });
}
}
You can see how this works in a demo at: http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-bounds-tutorial-with-kineticjs/
[Edit: specify where each code goes]
I put the pieces together into a working snippet below. I did find one unfortunate thing. It’s possible for the user to drag the pink box fast enough to go right through the obstacle—KineticJS can’t react fast enough to stop a very fast drag.
Also--oops on me. I corrected some missing parentheses in the theyAreColliding function above.
The dragBoundFunc goes as an addition to the box constructor (see code below).
You can test if the user has a goal by testing in the box’s “dragmove” handler, like this:
box.on('dragmove', function() {
if (theyAreColliding(box, target)) {
// box touched the goal
alert("Goal!");
}
});
Here is code and a Fiddle: http://jsfiddle.net/uCAys/