2

I want to check if an animated circle element collides (overlaps) with an animated Path Element in a set of Path Elements.

To make the example easier to understand I animated circles and want you to show me, how you can make the green circle appear red, as soon one of the black circles collides with it:

http://jsfiddle.net/329pK/2/

The Code from the Fiddle:

JS
var paper = Raphael("canvas", 800, 800);
var cx = 400;
var cy = 400;   
// Helpers
function rand(min, max) {
    return Math.random() * (max - min) + min;
}

var bigCircle = paper.circle(cx, cy, 500);
function flyMeteor(){
    var ptOnCircle = bigCircle.getPointAtLength(rand(1,bigCircle.getTotalLength()));
    var anim = Raphael.animation({
        fill: 'black',
        opacity: 0,
        cx: ptOnCircle.x,
        cy: ptOnCircle.y,
        stroke: 0,
        r: 0
    },1200,function(){
        this.remove();
    });
    var circle = paper.circle(cx, cy, 4).attr({
        fill:'black',
        stroke: 0
    }).animate(anim);
};
setInterval(function(){
    flyMeteor();
},200); 

var circle = paper.circle(250, 250, 80).attr({
    fill:'green',
    stroke: 0
});

HTML
<div id="canvas"></div>

Thank you very much for your help!

Simon S.
  • 563
  • 4
  • 21

1 Answers1

0

I'm not sure if there's an easy answer to this one. There are a few SVG methods like referenced here Hit-testing SVG shapes? but I'm not sure they could really be used for this. It also depends if its just circles, or if the circles are just placeholders for something more complex. If its circles, you could follow collision detection like Circle Collision Javascript which I've used in an example below...

For checking, I'm checking all objects outside the animation. This feels a bit clunky, and it would be better to have inside the animation somehow, but haven't seen a way one can do this (you could do your own animate func).

fiddle here http://jsfiddle.net/RvvXL/1/

circle.data('myAnim', anim);

....

function collision (p1x, p1y, r1, p2x, p2y, r2) {
    var a;
    var x;
    var y;

    a = r1 + r2;
    x = p1x - p2x;
    y = p1y - p2y;

    if ( a > Math.sqrt( (x*x) + (y*y) ) ) {
       return true;
    } else {
        return false;
    }   
}

....

setInterval( function() {   // maybe use requestAnimationFrame
    paper.forEach( function(el) { 
        if( el.type=='circle' ) { 
            if( collision( el.attr('cx'), el.attr('cy'), el.attr('r'), bigCircle.attr('cx'), bigCircle.attr('cy'), bigCircle.attr('r') ) ) {
                if( el.data('myAnim') ) {
                    el.stop( el.data('myAnim') );
                    el.remove();
                }
            };
        }
   } );
Community
  • 1
  • 1
Ian
  • 13,724
  • 4
  • 52
  • 75