Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Get the 2D context from the canvas in
- // our HTML page
- var canvas = document.getElementById("gameCanvas");
- var context = canvas.getContext("2d");
- // Key constants
- // Go here for a list of key codes :
- // https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
- var KEY_SPACE = 32;
- var KEY_LEFT = 37;
- var KEY_UP = 38;
- var KEY_RIGHT = 39;
- var KEY_DOWN = 40;
- var SCREEN_WIDTH = canvas.width;
- var SCREEN_HEIGHT = canvas.height;
- var spawnTimer = 0;
- var ASTEROID_SPEED = 0.8;
- var PLAYER_SPEED = 2;
- var PLAYER_TURN_SPEED = 0.07;
- var BULLET_SPEED = 2.5;
- // this creates the background
- var backgroundImage = document.createElement("img");
- backgroundImage.src = "earth.png";
- // set up some event handlers to process keyboard input
- window.addEventListener('keydown', function(evt) {onKeyDown(evt);}, false);
- window.addEventListener('keyup', function(evt) {onKeyUp(evt); }, false);
- var startFrameMillis = Date.now();
- var endFrameMillis = Date.now();
- function getDeltaTime() // Only call this function once per frame
- {
- endFrameMillis = startFrameMillis;
- startFrameMillis = Date.now();
- var deltaTime = (startFrameMillis - endFrameMillis) * 0.001;
- if (deltaTime > 1) // validate that the delta is within range
- {
- deltaTime = 1;
- }
- return deltaTime;
- }
- // This creats the player object and assigns it some properties
- var player = {
- image: document.createElement("img"),
- x: SCREEN_WIDTH/2,
- y: SCREEN_HEIGHT/2,
- width: 93,
- height: 80,
- directionX: 0,
- directionY: 0,
- angularDirection: 0,
- rotation: 0,
- isDead: false
- };
- //set the image for the player to use
- player.image.src = "ship.png"
- //Create an array to store our asteroids
- var asteroids = [];
- //rand(floor,ceil)
- //Return a random number within the range of the 2 input variables
- function rand(floor,ceil)
- {
- return Math.floor( (Math.random()* (ceil-floor)) +floor );
- }
- //Create a new random asteroid and add it to our asteroids array.
- //We'll give the asteroid a random position (just off screen) and
- //set it moving towards the player
- function spawnAsteroid()
- {
- //make a random vairable to specify which asteroid to use
- //(small, medium, large)
- var type = rand(0, 3);
- // create the new asteroid
- var asteroid = {};
- asteroid.image = document.createElement("img");
- asteroid.image.src = "rock_large.png";
- asteroid.width = 69;
- asteroid.height = 75;
- //to set a random position just off screen we'll start at the center of the
- //screen then move in a random direction by the width of the screen
- var x = SCREEN_WIDTH/2;
- var y = SCREEN_HEIGHT/2;
- var dirX = rand(-10, 10);
- var dirY = rand(-10, 10);
- // normalise the direction (hypotenuse of a tryangle formed
- // by x, y will equal 1)
- var magnitude = (dirX * dirX) + (dirY * dirY);
- if(magnitude != 0)
- {
- var oneOverMag = 1 / Math.sqrt(magnitude);
- dirX *= oneOverMag;
- dirY *= oneOverMag;
- }
- // now we can multiply the dirX/Y by the screen width to move that amount from
- //the center of the screen
- var movX = dirX * SCREEN_WIDTH;
- var movY = dirY * SCREEN_HEIGHT;
- // add the direction to the origional position to get the starting position of the
- //asteroid
- asteroid.x = x + movX;
- asteroid.y = y + movY;
- // now the easy way to set the velocity so the asteroid moves towards the
- //center of the screen is to just reverse the direction we found earlier
- asteroid.velocityX = -dirX * ASTEROID_SPEED;
- asteroid.velocityY = -dirY * ASTEROID_SPEED;
- // finally we can add our new asteroid to the end of our asteroids array
- asteroids.push(asteroid);
- }
- //create all the bullets in the game
- var bullets = [];
- function playerShoot()
- {
- var bullet = {
- image: document.createElement("img"),
- x: player.x,
- y: player.y,
- width: 5,
- height: 5,
- velocityX: 0,
- velocityY: 0
- };
- // set the image for the bullet to use
- bullet.image.src = "bullet.png";
- // start off with a velocity that shoots the bullet straight up
- var velX = 0;
- var velY = 1;
- // now rotate this vector according to the ships current rotation
- var s = Math.sin(player.rotation);
- var c = Math.cos(player.rotation);
- var xVel = (velX * c) - (velY * s);
- var yVel = (velX * s) + (velY * c);
- // dont bother storing a direction and calculating the
- //velocity every frame, because it wont change.
- //just store the pre-calculated velocity
- bullet.velocityX = xVel * BULLET_SPEED;
- bullet.velocityY = yVel * BULLET_SPEED;
- //finally add the bullet to the bullets array
- bullets.push(bullet);
- }
- var shootTimer = 0;
- var shoot = false;
- function onKeyDown(event)
- {
- if(event.keyCode == KEY_UP)
- {
- player.directionY = 1;
- }
- if(event.keyCode == KEY_DOWN)
- {
- player.directionY = -1;
- }
- if(event.keyCode == KEY_LEFT)
- {
- player.angularDirection = -1;
- }
- if(event.keyCode == KEY_RIGHT)
- {
- player.angularDirection = 1;
- }
- if(event.keyCode == KEY_SPACE && shootTimer <=0)
- {
- shootTimer += 0.3;
- playerShoot();
- }
- if(event.keyCode == KEY_SPACE)
- {
- shoot == true;
- }
- }
- function onKeyUp(event)
- {
- if(event.keyCode == KEY_SPACE)
- {
- shoot == false;
- }
- if(event.keyCode == KEY_UP)
- {
- player.directionY = 0;
- }
- if(event.keyCode == KEY_DOWN)
- {
- player.directionY = -0;
- }
- if(event.keyCode == KEY_LEFT)
- {
- player.angularDirection = 0;
- }
- if(event.keyCode == KEY_RIGHT)
- {
- player.angularDirection = 0;
- }
- }
- //tests if 2 rectangles are intersecting.
- //Pass in the x,y coordinates, width and height of each rectangle.
- //Returns 'true' if the rectangles are intersecting
- function intersects(x1, y1, w1, h1, x2, y2, w2, h2)
- {
- if(y2 + h2 < y1 ||
- x2 + w2 < x1 ||
- x2 > x1 + w1 ||
- y2 > y1 + h1)
- {
- return false;
- }
- return true;
- }
- function run()
- {
- context.fillStyle = "#1E90FF";
- context.fillRect (0,0,canvas.width, canvas.height);
- context.drawImage (backgroundImage,0 ,0);
- var deltaTime = getDeltaTime();
- // check player asteroid collision
- for (var i = 0; i < asteroids.length; i++)
- {
- if (player.isDead == false)
- {
- if (intersects (player.x, player.y,
- player.width,player.height,
- asteroids[i].x, asteroids[i].y,
- asteroids[i].width, asteroids[i].height) == true)
- {
- asteroids.splice(i, 1);
- player.isDead = true;
- break;
- }
- }
- }
- //update the shoot timer
- if(shootTimer > 0)
- shootTimer -= deltaTime;
- if(player.isDead == false)
- {
- //update all the bullets
- for(var i=0; i<bullets.length; i++)
- {
- bullets[i].x += bullets[i].velocityX;
- bullets[i].y += bullets[i].velocityY;
- }
- if(shoot == false) {
- for(var i=0; i<bullets.length; i++)
- {
- //check to see if the bullet has gone out of the screen boundries
- // and if so kill it
- if(bullets[i].x < -bullets[i].width ||
- bullets[i].x > SCREEN_WIDTH ||
- bullets[i].y < -bullets[i].width ||
- bullets[i].y > SCREEN_HEIGHT)
- {
- //remove 1 element at position i
- bullets.splice(i, 1);
- //because we are deleting elements from the middle of the
- //aray, we can only remove 1 bullet at a time. So, as soon as we
- //remove 1 bullet stop.
- break;
- }
- }
- //draw all the bullets
- for(var i=0; i<bullets.length; i++)
- {
- context.drawImage(bullets[i].image,
- bullets[i].x - bullets[i].width/2,
- bullets[i].y - bullets[i].height/2);
- }
- }
- }
- //calculate sin and cos for the player's current rotation
- if(player.isDead == false)
- {
- var s = Math.sin(player.rotation);
- var c = Math.cos(player.rotation);
- //so figure out what the player's velocity will be based on the current rotation
- //(so if the ship is moving forward, then it will move forward according to it's
- //rotation. Without this, the ship would just move up the screen when we pressed 'up',
- //regardless of which way it was rotated)
- // for an explanation of this formula, see http://en.wikipedia.org/wiki/Rotation_matrix
- var xDir = (player.directionX * c) - (player.directionY * s);
- var yDir = (player.directionX * s) + (player.directionY * c);
- var xVel = xDir * PLAYER_SPEED;
- var yVel = yDir * PLAYER_SPEED;
- player.x += xVel;
- player.y += yVel;
- player.rotation += player.angularDirection * PLAYER_TURN_SPEED;
- context.save();
- context.translate(player.x, player.y);
- context.rotate(player.rotation);
- context.drawImage(
- player.image, -player.width/2, -player.height/2);
- context.restore();
- }
- //wrap player around to the opposite position if
- //moved out of canvas bounds
- if (player.x + player.width < player.width/2)
- {
- player.x = canvas.width;
- }
- if (player.y + player.height < player.height/2)
- {
- player.y = canvas.height;
- }
- if (player.x > canvas.width + player.width/2)
- {
- player.x = 0;
- }
- if (player.y > canvas.height + player.height/2)
- {
- player.y = 0;
- }
- // update all the asteroids in the asteroids array
- for(var i=0; i<asteroids.length; i++)
- {
- // update the asteroids position according to its current velocity.
- // DONT forget to multiply by deltaTime to get a constant speed
- asteroids[i].x = asteroids[i].x + asteroids[i].velocityX;
- asteroids[i].y = asteroids[i].y + asteroids[i].velocityY;
- // TODO check if the asteroid has gone out of screen boundaries
- //if so, wrap the asteroid around the screen so it comes back
- //from the other side
- }
- // draw all of the asteroids
- for (var i=0; i<asteroids.length; i++)
- {
- context.drawImage(asteroids[i].image, asteroids[i].x, asteroids[i].y);
- }
- spawnTimer -= deltaTime;
- if(spawnTimer <= 0)
- {
- spawnTimer = 1;
- spawnAsteroid();
- }
- // check if any bullet intersects any asteroid. If so, kill them both
- for(var i=0; i<asteroids.length; i++)
- {
- for(var j=0; j<bullets.length; j++)
- {
- if(intersects(
- bullets[j].x, bullets[j].y,
- bullets[j].width, bullets[j].height,
- asteroids[i].x, asteroids[i].y,
- asteroids[i].width, asteroids[i].height) == true)
- {
- asteroids.splice(i, 1);
- bullets.splice(j, 1);
- break;
- }
- }
- }
- }
- //------------------Don't modify anything below here
- // This code will set up the framework so that the 'run' function is
- // called 60 times per second. We have some options to fall back on
- // in case the browser doesn't support our preferred method.
- (function() {
- var onEachFrame;
- if (window.requestAnimationFrame) {
- onEachFrame = function(cb) {
- var _cb = function() { cb(); window.requestAnimationFrame(_cb);}
- _cb();
- };
- } else if (window.mozRequestAnimationFrame) {
- onEachFrame = function(cb){
- var_cb = function(){ cb();
- window.mozRequestAnimationFrame(_cb);}
- _cb();
- };
- } else {
- onEachFrame = function(cb) {
- setInterval(cb, 1000/60);
- }
- }
- window.onEachFrame = onEachFrame;
- })();
- window.onEachFrame(run);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement