Advertisement
Guest User

Untitled

a guest
Apr 1st, 2015
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.73 KB | None | 0 0
  1. // Get the 2D context from the canvas in
  2. // our HTML page
  3.  
  4. var canvas = document.getElementById("gameCanvas");
  5. var context = canvas.getContext("2d");
  6.  
  7. // Key constants
  8. // Go here for a list of key codes :
  9. // https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
  10. var KEY_SPACE = 32;
  11. var KEY_LEFT = 37;
  12. var KEY_UP = 38;
  13. var KEY_RIGHT = 39;
  14. var KEY_DOWN = 40;
  15.  
  16. var SCREEN_WIDTH = canvas.width;
  17. var SCREEN_HEIGHT = canvas.height;
  18.  
  19. var spawnTimer = 0;
  20. var ASTEROID_SPEED = 0.8;
  21. var PLAYER_SPEED = 2;
  22. var PLAYER_TURN_SPEED = 0.07;
  23. var BULLET_SPEED = 2.5;
  24.  
  25. // this creates the background
  26. var backgroundImage = document.createElement("img");
  27. backgroundImage.src = "earth.png";
  28.  
  29. // set up some event handlers to process keyboard input
  30. window.addEventListener('keydown', function(evt) {onKeyDown(evt);}, false);
  31. window.addEventListener('keyup', function(evt) {onKeyUp(evt); }, false);
  32.  
  33. var startFrameMillis = Date.now();
  34. var endFrameMillis = Date.now();
  35.  
  36. function getDeltaTime() // Only call this function once per frame
  37. {
  38. endFrameMillis = startFrameMillis;
  39. startFrameMillis = Date.now();
  40. var deltaTime = (startFrameMillis - endFrameMillis) * 0.001;
  41. if (deltaTime > 1) // validate that the delta is within range
  42. {
  43. deltaTime = 1;
  44. }
  45. return deltaTime;
  46. }
  47.  
  48. // This creats the player object and assigns it some properties
  49. var player = {
  50. image: document.createElement("img"),
  51. x: SCREEN_WIDTH/2,
  52. y: SCREEN_HEIGHT/2,
  53. width: 93,
  54. height: 80,
  55. directionX: 0,
  56. directionY: 0,
  57. angularDirection: 0,
  58. rotation: 0,
  59. isDead: false
  60. };
  61. //set the image for the player to use
  62. player.image.src = "ship.png"
  63.  
  64. //Create an array to store our asteroids
  65. var asteroids = [];
  66.  
  67. //rand(floor,ceil)
  68. //Return a random number within the range of the 2 input variables
  69. function rand(floor,ceil)
  70. {
  71. return Math.floor( (Math.random()* (ceil-floor)) +floor );
  72. }
  73.  
  74. //Create a new random asteroid and add it to our asteroids array.
  75. //We'll give the asteroid a random position (just off screen) and
  76. //set it moving towards the player
  77. function spawnAsteroid()
  78. {
  79. //make a random vairable to specify which asteroid to use
  80. //(small, medium, large)
  81. var type = rand(0, 3);
  82.  
  83. // create the new asteroid
  84. var asteroid = {};
  85.  
  86. asteroid.image = document.createElement("img");
  87. asteroid.image.src = "rock_large.png";
  88. asteroid.width = 69;
  89. asteroid.height = 75;
  90.  
  91. //to set a random position just off screen we'll start at the center of the
  92. //screen then move in a random direction by the width of the screen
  93. var x = SCREEN_WIDTH/2;
  94. var y = SCREEN_HEIGHT/2;
  95.  
  96. var dirX = rand(-10, 10);
  97. var dirY = rand(-10, 10);
  98.  
  99. // normalise the direction (hypotenuse of a tryangle formed
  100. // by x, y will equal 1)
  101. var magnitude = (dirX * dirX) + (dirY * dirY);
  102. if(magnitude != 0)
  103. {
  104. var oneOverMag = 1 / Math.sqrt(magnitude);
  105. dirX *= oneOverMag;
  106. dirY *= oneOverMag;
  107. }
  108.  
  109. // now we can multiply the dirX/Y by the screen width to move that amount from
  110. //the center of the screen
  111. var movX = dirX * SCREEN_WIDTH;
  112. var movY = dirY * SCREEN_HEIGHT;
  113.  
  114. // add the direction to the origional position to get the starting position of the
  115. //asteroid
  116. asteroid.x = x + movX;
  117. asteroid.y = y + movY;
  118.  
  119. // now the easy way to set the velocity so the asteroid moves towards the
  120. //center of the screen is to just reverse the direction we found earlier
  121. asteroid.velocityX = -dirX * ASTEROID_SPEED;
  122. asteroid.velocityY = -dirY * ASTEROID_SPEED;
  123.  
  124. // finally we can add our new asteroid to the end of our asteroids array
  125. asteroids.push(asteroid);
  126. }
  127.  
  128. //create all the bullets in the game
  129. var bullets = [];
  130.  
  131. function playerShoot()
  132. {
  133. var bullet = {
  134. image: document.createElement("img"),
  135. x: player.x,
  136. y: player.y,
  137. width: 5,
  138. height: 5,
  139. velocityX: 0,
  140. velocityY: 0
  141. };
  142.  
  143. // set the image for the bullet to use
  144. bullet.image.src = "bullet.png";
  145.  
  146. // start off with a velocity that shoots the bullet straight up
  147. var velX = 0;
  148. var velY = 1;
  149.  
  150. // now rotate this vector according to the ships current rotation
  151. var s = Math.sin(player.rotation);
  152. var c = Math.cos(player.rotation);
  153.  
  154. var xVel = (velX * c) - (velY * s);
  155. var yVel = (velX * s) + (velY * c);
  156.  
  157. // dont bother storing a direction and calculating the
  158. //velocity every frame, because it wont change.
  159. //just store the pre-calculated velocity
  160. bullet.velocityX = xVel * BULLET_SPEED;
  161. bullet.velocityY = yVel * BULLET_SPEED;
  162.  
  163. //finally add the bullet to the bullets array
  164. bullets.push(bullet);
  165. }
  166.  
  167. var shootTimer = 0;
  168. var shoot = false;
  169. function onKeyDown(event)
  170. {
  171. if(event.keyCode == KEY_UP)
  172. {
  173. player.directionY = 1;
  174. }
  175. if(event.keyCode == KEY_DOWN)
  176. {
  177. player.directionY = -1;
  178. }
  179. if(event.keyCode == KEY_LEFT)
  180. {
  181. player.angularDirection = -1;
  182. }
  183. if(event.keyCode == KEY_RIGHT)
  184. {
  185. player.angularDirection = 1;
  186. }
  187. if(event.keyCode == KEY_SPACE && shootTimer <=0)
  188. {
  189. shootTimer += 0.3;
  190. playerShoot();
  191. }
  192. if(event.keyCode == KEY_SPACE)
  193. {
  194. shoot == true;
  195. }
  196.  
  197. }
  198. function onKeyUp(event)
  199. {
  200. if(event.keyCode == KEY_SPACE)
  201. {
  202. shoot == false;
  203. }
  204. if(event.keyCode == KEY_UP)
  205. {
  206. player.directionY = 0;
  207. }
  208. if(event.keyCode == KEY_DOWN)
  209. {
  210. player.directionY = -0;
  211. }
  212. if(event.keyCode == KEY_LEFT)
  213. {
  214. player.angularDirection = 0;
  215. }
  216. if(event.keyCode == KEY_RIGHT)
  217. {
  218. player.angularDirection = 0;
  219. }
  220. }
  221.  
  222. //tests if 2 rectangles are intersecting.
  223. //Pass in the x,y coordinates, width and height of each rectangle.
  224. //Returns 'true' if the rectangles are intersecting
  225. function intersects(x1, y1, w1, h1, x2, y2, w2, h2)
  226. {
  227. if(y2 + h2 < y1 ||
  228. x2 + w2 < x1 ||
  229. x2 > x1 + w1 ||
  230. y2 > y1 + h1)
  231. {
  232. return false;
  233. }
  234. return true;
  235. }
  236.  
  237. function run()
  238. {
  239. context.fillStyle = "#1E90FF";
  240. context.fillRect (0,0,canvas.width, canvas.height);
  241. context.drawImage (backgroundImage,0 ,0);
  242. var deltaTime = getDeltaTime();
  243.  
  244. // check player asteroid collision
  245.  
  246. for (var i = 0; i < asteroids.length; i++)
  247. {
  248. if (player.isDead == false)
  249. {
  250. if (intersects (player.x, player.y,
  251. player.width,player.height,
  252. asteroids[i].x, asteroids[i].y,
  253. asteroids[i].width, asteroids[i].height) == true)
  254. {
  255. asteroids.splice(i, 1);
  256. player.isDead = true;
  257. break;
  258. }
  259. }
  260. }
  261.  
  262. //update the shoot timer
  263. if(shootTimer > 0)
  264. shootTimer -= deltaTime;
  265.  
  266. if(player.isDead == false)
  267. {
  268.  
  269. //update all the bullets
  270. for(var i=0; i<bullets.length; i++)
  271. {
  272. bullets[i].x += bullets[i].velocityX;
  273. bullets[i].y += bullets[i].velocityY;
  274. }
  275.  
  276. if(shoot == false) {
  277. for(var i=0; i<bullets.length; i++)
  278. {
  279. //check to see if the bullet has gone out of the screen boundries
  280. // and if so kill it
  281. if(bullets[i].x < -bullets[i].width ||
  282. bullets[i].x > SCREEN_WIDTH ||
  283. bullets[i].y < -bullets[i].width ||
  284. bullets[i].y > SCREEN_HEIGHT)
  285. {
  286. //remove 1 element at position i
  287. bullets.splice(i, 1);
  288. //because we are deleting elements from the middle of the
  289. //aray, we can only remove 1 bullet at a time. So, as soon as we
  290. //remove 1 bullet stop.
  291. break;
  292. }
  293. }
  294.  
  295. //draw all the bullets
  296. for(var i=0; i<bullets.length; i++)
  297. {
  298. context.drawImage(bullets[i].image,
  299. bullets[i].x - bullets[i].width/2,
  300. bullets[i].y - bullets[i].height/2);
  301. }
  302. }
  303. }
  304.  
  305. //calculate sin and cos for the player's current rotation
  306. if(player.isDead == false)
  307. {
  308. var s = Math.sin(player.rotation);
  309. var c = Math.cos(player.rotation);
  310.  
  311.  
  312. //so figure out what the player's velocity will be based on the current rotation
  313. //(so if the ship is moving forward, then it will move forward according to it's
  314. //rotation. Without this, the ship would just move up the screen when we pressed 'up',
  315. //regardless of which way it was rotated)
  316. // for an explanation of this formula, see http://en.wikipedia.org/wiki/Rotation_matrix
  317. var xDir = (player.directionX * c) - (player.directionY * s);
  318. var yDir = (player.directionX * s) + (player.directionY * c);
  319. var xVel = xDir * PLAYER_SPEED;
  320. var yVel = yDir * PLAYER_SPEED;
  321.  
  322. player.x += xVel;
  323. player.y += yVel;
  324.  
  325. player.rotation += player.angularDirection * PLAYER_TURN_SPEED;
  326.  
  327. context.save();
  328. context.translate(player.x, player.y);
  329. context.rotate(player.rotation);
  330. context.drawImage(
  331. player.image, -player.width/2, -player.height/2);
  332. context.restore();
  333. }
  334.  
  335. //wrap player around to the opposite position if
  336. //moved out of canvas bounds
  337.  
  338. if (player.x + player.width < player.width/2)
  339. {
  340. player.x = canvas.width;
  341. }
  342. if (player.y + player.height < player.height/2)
  343. {
  344. player.y = canvas.height;
  345. }
  346. if (player.x > canvas.width + player.width/2)
  347. {
  348. player.x = 0;
  349. }
  350. if (player.y > canvas.height + player.height/2)
  351. {
  352. player.y = 0;
  353. }
  354.  
  355. // update all the asteroids in the asteroids array
  356. for(var i=0; i<asteroids.length; i++)
  357. {
  358. // update the asteroids position according to its current velocity.
  359. // DONT forget to multiply by deltaTime to get a constant speed
  360. asteroids[i].x = asteroids[i].x + asteroids[i].velocityX;
  361. asteroids[i].y = asteroids[i].y + asteroids[i].velocityY;
  362.  
  363. // TODO check if the asteroid has gone out of screen boundaries
  364. //if so, wrap the asteroid around the screen so it comes back
  365. //from the other side
  366. }
  367.  
  368. // draw all of the asteroids
  369. for (var i=0; i<asteroids.length; i++)
  370. {
  371. context.drawImage(asteroids[i].image, asteroids[i].x, asteroids[i].y);
  372. }
  373.  
  374. spawnTimer -= deltaTime;
  375. if(spawnTimer <= 0)
  376. {
  377. spawnTimer = 1;
  378. spawnAsteroid();
  379. }
  380.  
  381.  
  382. // check if any bullet intersects any asteroid. If so, kill them both
  383. for(var i=0; i<asteroids.length; i++)
  384. {
  385. for(var j=0; j<bullets.length; j++)
  386. {
  387. if(intersects(
  388. bullets[j].x, bullets[j].y,
  389. bullets[j].width, bullets[j].height,
  390. asteroids[i].x, asteroids[i].y,
  391. asteroids[i].width, asteroids[i].height) == true)
  392. {
  393. asteroids.splice(i, 1);
  394. bullets.splice(j, 1);
  395. break;
  396. }
  397. }
  398. }
  399. }
  400.  
  401. //------------------Don't modify anything below here
  402.  
  403. // This code will set up the framework so that the 'run' function is
  404. // called 60 times per second. We have some options to fall back on
  405. // in case the browser doesn't support our preferred method.
  406. (function() {
  407. var onEachFrame;
  408. if (window.requestAnimationFrame) {
  409. onEachFrame = function(cb) {
  410. var _cb = function() { cb(); window.requestAnimationFrame(_cb);}
  411. _cb();
  412. };
  413. } else if (window.mozRequestAnimationFrame) {
  414. onEachFrame = function(cb){
  415. var_cb = function(){ cb();
  416. window.mozRequestAnimationFrame(_cb);}
  417. _cb();
  418. };
  419. } else {
  420. onEachFrame = function(cb) {
  421. setInterval(cb, 1000/60);
  422. }
  423. }
  424.  
  425. window.onEachFrame = onEachFrame;
  426. })();
  427.  
  428. window.onEachFrame(run);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement