function start() { missiles = []; preloadSound('boom'); preloadSound('charge'); playBackgroundSound('r-type.mp3'); } function update() { clearScreenWithColor("black"); if (! (mouseX > 0 && mouseY > 0)) return; for (i in missiles) { m = missiles[i]; m.move(); m.draw(); if (distance(m.x, m.y, mouseX, mouseY) < 10) die(); } if (random(FPS) == 0) { playSound('charge', 0.3); missiles[missiles.length] = new missile(canvas.width + 100, random(canvas.height)); } text(missiles.length, 40, 40, "white", 10); } function missile(x, y) { this.x = x; this.y = y; this.rotation = 0; this.xSpeed = 0; this.ySpeed = 0; this.move = function() { m.xSpeed += (mouseX - m.x) / 3000; m.ySpeed += (mouseY - m.y) / 3000; this.x += this.xSpeed; this.y += this.ySpeed; this.rotation = this.calculateRotation(); } this.calculateRotation = function() { var offset = 0; var trigOperator = Math.asin; xDiff = this.x - mouseX; yDiff = this.y - mouseY; if (xDiff < 0 && yDiff < 0) { trigOperator = Math.asin; offset = 0; } else if (xDiff < 0 && yDiff > 0) { trigOperator = Math.acos; offset = 270; } else if (xDiff > 0 && yDiff < 0) { trigOperator = Math.acos; offset = 90; } else if (xDiff > 0 && yDiff > 0) { trigOperator = Math.asin; offset = 180; } var best = offset + trigOperator(Math.abs(this.y - mouseY) / distance(this.x, this.y, mouseX, mouseY)) / (Math.PI / 180); var correction = this.rotation - best; if (correction > 180) correction -= 360; else if (correction < -180) correction += 360; return this.rotation - correction / 30; } this.draw = function() { save(); translate(this.x, this.y); rotate(this.rotation); rectangle(-40, -6, 20, 12, "white"); triangle(0, 0, -20, -6, -20, 6, "white"); triangle(-40, -4, -40, 4, -22 - Math.abs(this.xSpeed) * 5, 0, "yellow"); triangle(-40, -3, -40, 3, -22 - Math.abs(this.xSpeed) * 2, 0, "red"); restore(); } } function die() { playSound('boom'); for (i = 0; i < 200; i++) circle(mouseX + (0.5 - random(100)/100) * i, mouseY + (0.5 - random(100)/100) * i, 3 * (1-i/200), randomAlternative(["yellow", "red"])); circle(mouseX, mouseY, 10, "red"); stopUpdate(); }