Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCYPE html>
- <html>
- <head>
- <title> My Canvas </title>
- <meta charset = "utf-8" />
- <style>
- canvas {
- background-image: url("sprites/bg_background.png");
- }
- </style>
- </head>
- <body>
- <h1> Missile Collector! </h1>
- <h2 onclick = "showCoords(event)">
- <p id="demo"></p>
- <canvas id="myCanvas" width="540" height="960"></canvas>
- <script>
- // Initialize
- var canvas = document.getElementById("myCanvas")
- var ctx = canvas.getContext("2d");
- var x = 270;
- // Get mouse position
- function showCoords(event) {
- x = event.clientX;
- var coords = "X coords: " + x;
- document.getElementById("demo").innerHTML = coords;
- }
- // Score Veriables
- var score = 0;
- var health = 5;
- // Player Veriables
- var player = new Image();
- var playerX = 270;
- var playerY = 840;
- const playerThick = 48;
- const spd = 4;
- // Missle Veriables
- var missile = new Image();
- const missileXThick = 42;
- const missileYThick = 56;
- var missileX = Math.floor((Math.random() * canvas.width-missileXThick) + 1+missileXThick);
- var missileY = 0;
- // Draw the score
- function drawScore() {
- ctx.font = "24px Arial";
- ctx.fillStyle = "#000000";
- ctx.fillText("Score: " + score, 5, 25);
- ctx.fillText("Health: " + health, 5, 50);
- // Game Over
- if (health <= 0) {
- alert("Game Over");
- }
- }
- // Reset the Missle
- function missileReset() {
- missileX = Math.floor((Math.random() * canvas.width-missileXThick) + 1+missileXThick);
- missileY = 0;
- }
- // Draw the Missle
- function drawMissile() {
- ctx.drawImage(missile, missileX, missileY)
- missile.src = 'sprites/spr_missile.png';
- missileY += 5;
- missileCollision();
- }
- // Draw Player
- function drawPlayer() {
- ctx.drawImage(player, playerX, playerY);
- player.src = 'sprites/spr_bowl.png';
- playerX = x-playerThick/2;
- }
- // Collisions
- function missileCollision() {
- if (missileY = playerY-missileYThick && missileX > x && missileX+missileXThick < x+playerThick) {
- score += 1;
- missileReset();
- }
- if (missileY >= canvas.height-missileYThick) {
- health -= 1;
- missileReset();
- }
- }
- // Draw Everything
- function draw() {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.onclick = function() {showCoords(event)};
- if (health > 0) {
- drawPlayer();
- drawMissile();
- drawScore();
- }
- requestAnimationFrame(draw);
- }
- draw();
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement