Search code examples
javascriptjquerycsscollisiondetection

Collision Detection between images rotated using CSS animations


I'm using CSS animations and jQuery to move cars in a crossroads (top point of view) to simulate a driving license quiz. The user has to choose the crossing order by clicking over the cars.

Sample Image: http://i40.tinypic.com/717fc9.jpg

Each car has properties and an animation like this for example: blue car turning RIGHT (different from image):

#auto-b {
    left: 320px;
    top: 150px;
    -webkit-transform: rotate(180deg);
}

.animated #auto-b {
    -webkit-animation-name: move-b;
    -webkit-animation-fill-mode: forwards;
}

@-webkit-keyframes move-b {

    30% {
        left: 260px;
        top: 150px;
        -webkit-transform: rotate(180deg);
    }
    60% {
        left: 214px;
        top: 120px;
        -webkit-transform: rotate(270deg);
    }

    100% {
        top: 30px;
        left: 214px;
        -webkit-transform: rotate(270deg);
    }
}

The thing I'm not figuring out is how can I detect if two cars collide since they are rotated (turning).

Play button function:

$('#play').on('click', play);

function play(){    
    $('.auto').removeClass('selected');
    $('#incrocio').addClass('animated');    
    interval = setInterval(crash,1);
}

Crash function (only work with red and green cars collision because they don't rotate):

function crash(){

    var autoA = $('#auto-a').position();    
    var autoB = $('#auto-b').position();
    var autoC = $('#auto-c').position();    
    var top1 = autoA.top+10;
    var top2 = autoA.top-10;
    var left1 = autoA.left+10;
    var left2 = autoA.left-10;  

    if (top1 > autoC.top && top2 < autoC.top && left1 > autoC.left && left2 < autoC.left) {
        console.log("boom");
        $('#incrocio').removeClass('animated');
        alert("BOOM!");
        i = 1;
        carsArray = [];
        clearInterval(interval);
    }
}

Is there an easy way to detect any kind of collision between every image that has class ".auto"?

I also thought about calculating every point of the rectangle and checking if any of them is inside an other rectangle (car). However I can only get the top-left point and not the others.

Any solutions?

Thanks in advance!


Solution

  • Use Jquery/javascript to draw the animation of the cars. using css3 animation is a very bad choice of detecting events or to detect the collision.

    [SOLVED]

    while using the jquery use the below plugin for easy detection.

    http://plugins.jquery.com/overlaps/

    http://yckart.github.io/jquery.overlaps.js/

    [SOLVED]

    Hoping you had understood my points.