Im making a collision checking system with jQuery however it doesn’t seem to work. There are two buttons. You can move one button with the right key. Once the buttons collide one of the buttons should change font colour. Right now, the button will always change colour even if its not touching the other button. Try it out, if you have some problems understanding me.
Thanks,
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>my website</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$(document).keydown(function(event) {
if ( event.which == 39){
$('.button0 input').animate({'left': '+='+Math.cos(0*Math.PI/180) *30+'px','top': '+='+Math.sin(0*Math.PI/180) *30+'px'},30);
};
button0button1();
});
function button0button1(){
var div1=$('.button0 input');
var div2=$('.button1 input');
if ((div1.offset().top+div1.outerHeight(true)) < div2.offset().top || div1.offset().top > (div2.offset().top+div2.outerHeight(true)) || (div1.offset().left+div1.outerWidth(true)) < div2.offset().left || div1.offset().left > (div2.offset().left+div2.outerWidth(true))){
$('.button0 input').css('color', 'rgb(0, 128, 255)');
};
};
});
</script>
<style type="text/css">
.button0 input{
position:fixed;
left:30px;
top:213px;
font-family:MS Shell Dlg 2;
font-size:8px;
font-weight:NORMAL;
}
.button1 input{
position:fixed;
left:185px;
top:217px;
font-family:MS Shell Dlg 2;
font-size:8px;
font-weight:NORMAL;
}
</style>
<body>
<div class="button0"><input type="button" style="width: 73px;height: 67px;" value="Button"/></div>
<div class="button1"><input type="button" style="width: 61px;height: 56px;" value="Button"/></div>
</body>
</html>
I haven’t checked all the code (it’s a bit convoluted in its current form), but I identified two problems:
1) You got at least one of the comparison operators wrong:
(div1.offset().left+div1.outerWidth(true)) < div2.offset().left, should be>;2) Since the animate doesn’t immediatly change the position of your components, you should call
button0button1as a callback to animate, otherwise the buttons will collide during/at the end of the animation, but the code will report them as not colliding.