- This topic is empty.
Viewing 1 post (of 1 total)
Viewing 1 post (of 1 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Collision Detection in JS
So, I was trying to build a sample game using Web technologies, for no other reason but the fact that I love computer games.
Now, I need to see if two objects are collided (maybe the bullet with the enemy or mario with the mushroom). I searched google and found nothing so, tried to do it myself and came up with this. I made a very simple code piece which can do that:
$(".box").draggable({ drag: function(){ var $box1 = $("#box1"), $box2 = $('#box2'), $box1_width = $box1.width(), $box1_height = $box1.height(), $box2_width = $box2.width(), $box2_height = $box2.height();
if ( $box1.offset()['left'] + $box1_width > $box2.offset()['left'] && $box1.offset()['top'] + $box1_height > $box2.offset()['top'] && $box1.offset()['left'] < $box2.offset()['left'] + $box2_width && $box1.offset()['top'] < $box2.offset()['top'] + $box2_height ) { $box1.css('background', 'red'); console.log('collided!'); } else { $box1.css('background', '#123'); } } }); $("#box2").draggable();
It checkes the edges and it works fine with square-like objects. So, here's my questions:
1. How can I detect which side these objects have collision?
2. Can we have this work with non-squares? (really not necessary, I imagine it consume alot of resources.)
3. How to optimize it?
Thanks guys!