// Utility functions for a game to // detect collisopns and allow objects // to bouce off the edges or // be constrained to them function randomlyPlace(thing) { thing.x = Math.random() * (gCanvas.width - thing.width); thing.y = Math.random() * (gCanvas.height - thing.height); } // reverse the x and y speeds if overlapping the edges function bounceOffEdges(thing) { // bounce off the edges in Y direction if (thing.y + thing.height > gCanvas.height) { thing.y = gCanvas.height - thing.height; thing.yspeed *= -1; }else if (thing.y < 0){ thing.y = 0; thing.yspeed *= -1; } // bounce off the edges in X direction if (thing.x + thing.width > gCanvas.width) { thing.x = gCanvas.width - thing.width; thing.xspeed *= -1; }else if (thing.x < 0){ thing.x = 0; thing.xspeed *= -1; } } // limit the x and y positions if they would // go outside the canvas area function constrainToEdges(thing) { // if beyond the edges, limit in the X direction if (thing.x < 0){ thing.x = 0; }else if (thing.x > gCanvas.width - thing.width){ thing.x = gCanvas.width - thing.width; } // if beyond the edges, limit in the X direction if (thing.y < 0){ thing.y = 0; }else if (thing.y > gCanvas.height - thing.height){ thing.y = gCanvas.height - thing.height; } } // detect whether two objects have collided function detectCollision(thing1,thing2) { var collided = true; if (thing1.x> thing2.x + thing2.width) collided = false; if (thing1.x + thing1.width < thing2.x ) collided = false; if (thing1.y > thing2.y + thing2.height) collided = false; if (thing1.y + thing1.height < thing2.y) collided = false; return collided; }