Hey, all! I'm trying to figure out how to add collision detection to the following code but I'm having trouble trying to figure out how to pull in the x and y coordinates of the different eggs that are falling randomly. Would you be able to tell me what I'm doing wrong? Thank you!
<html>
<style>
#playingArea {
position: absolute;
top: 1;
left: 1;
width: 750;
height: 720;
z-index: 2;
}
#basket {
position: absolute;
top: 650;
left: 228;
width: 100;
height: 145;
}
</style>
<script type="text/javascript" language="Javascript">
var basket;
var basketLeft = 228;
function keyListener(e) {
document.getElementById("si"+i).style.top=eggsTop;
document.getElementById("si"+i).style.left=eggsLeft;
if (!e || (typeof(e)=="undefined")) { e = window.event; }
if (e.keyCode==37 && basketLeft > 0) {
basketLeft -= 8;
basket.style.left = basketLeft + 'px' ;
if (basket.style.left < eggsLeft + 65 &&
basket.style.left + basket.style.width > eggsLeft &&
basket.style.top < eggsTop + 84 &&
basket.style.height + basket.style.top > eggsTop) {
console.log("collision");
}
}
if (e.keyCode==39 && basketLeft < 436){
basketLeft += 8;
basket.style.left = basketLeft + 'px' ;
}
}
function init() {
basket=document.getElementById('basket');
document.onkeydown=keyListener;
fall();
}
grphcs=new Array(5)
Image0=new Image();
Image0.src=grphcs[0]="egg.png";
Image1=new Image();
Image1.src=grphcs[1]="egg_2.png";
Image2=new Image();
Image2.src=grphcs[2]="egg_3.png";
Image3=new Image();
Image3.src=grphcs[3]="egg_4.png";
Image4=new Image();
Image4.src=grphcs[4]="egg_5.png";
Amount=5;
Ypos=new Array();
Xpos=new Array();
Speed=new Array();
Step=new Array();
Cstep=new Array();
var Stop=false;
for(i=0;i<Amount;i++) {
var P=Math.floor(Math.random()*grphcs.length);
rndPic=grphcs[P];
document.write('<img id="si'+i+'" src="'+rndPic+'"style="position:absolute;top:0px;left:0px">');
}
WinHeight=document.body.clientHeight;
WinWidth=document.body.clientWidth;
for(i=0;i<Amount;i++) {
Ypos[i]=Math.round(Math.random()*WinHeight);
Xpos[i]=Math.round(Math.random()*WinWidth);
Speed[i]=Math.random()*5+3;
Cstep[i]=0;
Step[i]=Math.random()*0.1+0.05;
}
function fall() {
if(Stop)
{clear();
return;
}
var WinHeight=document.body.clientHeight-100;
var WinWidth=document.body.clientWidth-500;
for(i=0;i<Amount;i++) {
sy=Speed[i]*Math.sin(90*Math.PI/180);
sx=Speed[i]*Math.cos(Cstep[i]);
Ypos[i]+=sy;
Xpos[i]+=sx;
if(Ypos[i]>WinHeight) {
Ypos[i]=60;
Xpos[i]=Math.round(Math.random()*WinWidth);
Speed[i]=Math.random()*5+3;
}
else
{
document.getElementById("si"+i).style.left=Math.min(WinWidth,Xpos[i])-200;
document.getElementById("si"+i).style.top=Ypos[i];
}
Cstep[i]+=Step[i];
}
setTimeout('fall()',20);
}
setTimeout("Stop=true",30000);
function clear() {
for(i=0;i<Amount;i++)
document.getElementById("si"+i).style.display='none';
}
</script>
<body onload="init()";>
<div id= "basket">
<img src= "bottle.png">
</div>
<div id= "playingArea">
</div>
</body>
</html>