You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

game.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. let Vec2 = require("./vec2");
  2. function randint(min, max) {
  3. return Math.floor(Math.random() * (max - min + 1)) + min;
  4. }
  5. function random(min, max) {
  6. return Math.random() * (max - min + 1) + min;
  7. }
  8. function diff(n1, n2) {
  9. return Math.abs(n1 - n2);
  10. }
  11. function createImage(url) {
  12. var img = document.createElement("img");
  13. img.src = url;
  14. return img;
  15. }
  16. function background(ctx, camera, offset) {
  17. if (!background.cache) {
  18. let cache = [];
  19. let n = 1000;
  20. for (let i = 0; i < n; ++i) {
  21. let parallax = random(5.6, 9);
  22. cache.push({
  23. x: randint(0, window.innerWidth * parallax),
  24. y: randint(0, window.innerHeight * parallax),
  25. p: parallax
  26. });
  27. }
  28. background.cache = cache;
  29. }
  30. let cx = camera.x;
  31. let cy = camera.y;
  32. let cache = background.cache;
  33. let fs = ctx.fillStyle;
  34. ctx.fillStyle = "#FFFFFF";
  35. for (let i = 0, len = cache.length; i < len; ++i) {
  36. let p = cache[i];
  37. let x = (((p.x - cx) / p.p) + offset.x) % window.innerWidth;
  38. let y = (((p.y - cy) / p.p) + offset.y) % window.innerHeight;
  39. if (x < 0)
  40. x += window.innerWidth;
  41. if (y < 0)
  42. y += window.innerHeight;
  43. ctx.beginPath();
  44. ctx.arc(x, y, 1, 0, 2*Math.PI);
  45. ctx.closePath();
  46. ctx.fill();
  47. }
  48. ctx.fillStyle = fs;
  49. }
  50. window.addEventListener("resize", () => background.cache = null);
  51. class Animation {
  52. constructor({img, x, y, width, height, dwidth, dheight, wsteps, hsteps, nsteps, loop, fps, rot, offsetX, offsetY}) {
  53. loop = loop || false;
  54. fps = fps || 30;
  55. nsteps = nsteps || wsteps * hsteps;
  56. dwidth = dwidth || width;
  57. dheight = dheight || height;
  58. rot = rot || 0;
  59. offsetX = offsetX || 0;
  60. offsetY = offsetY || 0;
  61. this.img = img;
  62. this.x = x;
  63. this.y = y;
  64. this.offsetX = offsetX;
  65. this.offsetY = offsetY;
  66. this.rot = rot;
  67. this.width = width;
  68. this.height = height;
  69. this.dwidth = dwidth;
  70. this.dheight = dheight;
  71. this.wsteps = wsteps;
  72. this.hsteps = hsteps;
  73. this.wstep = 0;
  74. this.hstep = 0;
  75. this.step = 0;
  76. this.nsteps = nsteps;
  77. this.loop = loop;
  78. this.visible = true;
  79. this.onend = function(){};
  80. let interval = setInterval(() => {
  81. this.step += 1;
  82. if (this.step >= this.nsteps) {
  83. this.step = 0;
  84. this.wstep = 0;
  85. this.hstep = 0;
  86. if (!this.loop) {
  87. clearInterval(interval);
  88. this.onend();
  89. }
  90. return;
  91. }
  92. this.wstep += 1;
  93. if (this.wstep >= this.wsteps) {
  94. this.wstep = 0;
  95. this.hstep += 1;
  96. }
  97. }, 1000/fps);
  98. }
  99. animate(ctx) {
  100. if (!this.visible)
  101. return;
  102. ctx.translate(this.x, this.y);
  103. if (this.rot)
  104. ctx.rotate(this.rot);
  105. ctx.drawImage(
  106. this.img,
  107. this.wstep * this.width,
  108. this.hstep * this.width,
  109. this.width,
  110. this.height,
  111. this.offsetX,
  112. this.offsetY,
  113. this.dwidth,
  114. this.dheight
  115. );
  116. if (this.rot)
  117. ctx.rotate(-this.rot);
  118. }
  119. }
  120. class Entity {
  121. constructor(x, y, width, height, id, game) {
  122. this.pos = new Vec2(x, y);
  123. this.vel = new Vec2(0, 0);
  124. this.width = width;
  125. this.height = height;
  126. this.game = game;
  127. this.id = id;
  128. }
  129. draw(ctx) {}
  130. set(obj) {
  131. this.pos.set(obj.pos.x, obj.pos.y);
  132. this.vel.set(obj.vel.x, obj.vel.y);
  133. }
  134. update(dt) {
  135. this.pos.x += this.vel.x * dt;
  136. this.pos.y += this.vel.y * dt;
  137. }
  138. despawn() {}
  139. }
  140. let BulletImgs = {
  141. despawn: createImage("imgs/bullet_despawn.png")
  142. };
  143. let BulletSounds = {
  144. spawn: "sounds/bullet_spawn.wav",
  145. despawn: "sounds/bullet_despawn.wav"
  146. };
  147. class Bullet extends Entity {
  148. constructor(x, y, vel, id, ownerId, game) {
  149. super(x, y, 5, 5, id, game);
  150. this.vel.set(vel.x, vel.y);
  151. this.ownerId = ownerId;
  152. game.playSound(BulletSounds.spawn, this.pos);
  153. }
  154. draw(ctx, selfId) {
  155. if (selfId == this.ownerId) {
  156. ctx.fillStyle = "#FFFFFF";
  157. } else {
  158. ctx.fillStyle = "#FF0000";
  159. }
  160. ctx.beginPath();
  161. ctx.arc(-(this.width/2), -(this.height/2), this.width/2, 0, 2*Math.PI);
  162. ctx.closePath();
  163. ctx.fill();
  164. }
  165. set(obj) {
  166. super.set(obj);
  167. }
  168. despawn() {
  169. this.game.animate(new Animation({
  170. img: BulletImgs.despawn,
  171. x: this.pos.x,
  172. y: this.pos.y,
  173. width: 64,
  174. height: 64,
  175. dwidth: 16,
  176. dheight: 16,
  177. wsteps: 5,
  178. hsteps: 5
  179. }));
  180. this.game.playSound(BulletSounds.despawn, this.pos);
  181. }
  182. }
  183. let PlayerImgs = {
  184. thrust_back: createImage("imgs/player_thrust_back.png"),
  185. despawn: createImage("imgs/player_despawn.png")
  186. };
  187. let PlayerSounds = {
  188. despawn: "sounds/player_despawn.wav",
  189. thrust: "sounds/player_thrust.wav"
  190. };
  191. class Player extends Entity {
  192. constructor(x, y, id, rot, game) {
  193. super(x, y, 25, 60, id, game);
  194. this.rot = rot;
  195. this.rotVel = 0;
  196. this.keys = {};
  197. this.health = 0;
  198. this.thrustAnim = new Animation({
  199. img: PlayerImgs.thrust_back,
  200. x: this.pos.x,
  201. y: this.pos.y,
  202. width: 128,
  203. height: 128,
  204. dwidth: 64,
  205. dheight: 64,
  206. wsteps: 4,
  207. hsteps: 4,
  208. fps: 60,
  209. loop: true
  210. });
  211. this.thrustAnim.visible = false;
  212. game.animate(this.thrustAnim);
  213. this.thrustSound = document.createElement("audio");
  214. this.thrustSound.src = PlayerSounds.thrust;
  215. this.thrustSound.loop = true;
  216. this.thrustSound.play();
  217. this.thrustSound.volume = 0;
  218. }
  219. draw(ctx, selfId) {
  220. let h = Math.round((this.health * 2.4) + 15);
  221. if (selfId == this.id) {
  222. ctx.fillStyle = "rgb("+h+", "+h+", "+h+")";
  223. } else {
  224. ctx.fillStyle = "rgb("+h+", 0, 0)";
  225. }
  226. ctx.rotate(this.rot);
  227. if (this.keys.up) {
  228. this.thrustAnim.rot = this.rot;
  229. this.thrustAnim.x = this.pos.x;
  230. this.thrustAnim.y = this.pos.y;
  231. this.thrustAnim.offsetX = -this.thrustAnim.dwidth/2;
  232. this.thrustAnim.offsetY = this.thrustAnim.dwidth/2;
  233. if (this.keys.sprint) {
  234. this.thrustAnim.dheight = 100;
  235. if (this.id == selfId)
  236. this.game.screenShake(10);
  237. } else {
  238. this.thrustAnim.dheight = 64;
  239. }
  240. }
  241. ctx.beginPath();
  242. ctx.moveTo(0, -(this.height/2));
  243. ctx.lineTo(-this.width, this.height/2);
  244. ctx.lineTo(this.width, this.height/2);
  245. ctx.closePath();
  246. ctx.fill();
  247. ctx.rotate(-this.rot);
  248. //Draw pointers to far away players
  249. if (selfId == this.id) {
  250. this.game.entities.forEach((e) => {
  251. //Only draw players
  252. if (!(e instanceof Player))
  253. return;
  254. //Only draw far away players
  255. if (
  256. diff(e.pos.x, this.pos.x) < window.innerWidth / 2 &&
  257. diff(e.pos.y, this.pos.y) < window.innerHeight / 2
  258. ) {
  259. return;
  260. }
  261. let pos = e.pos.clone().sub(this.pos).normalize().scale(130);
  262. ctx.fillStyle = "rgb(255, 0, 0)";
  263. ctx.beginPath();
  264. ctx.arc(pos.x, pos.y, 5, 0, 2*Math.PI);
  265. ctx.closePath();
  266. ctx.fill();
  267. });
  268. }
  269. }
  270. set(obj) {
  271. super.set(obj);
  272. let lastHealth = this.health;
  273. this.rot = obj.rot;
  274. this.rotVel = obj.rotVel;
  275. this.keys = obj.keys;
  276. this.health = obj.health;
  277. if (this.id == this.game.id && lastHealth > obj.health) {
  278. this.game.screenShake(50);
  279. }
  280. }
  281. update(dt) {
  282. super.update(dt);
  283. this.rot += this.rotVel * dt;
  284. if (this.keys.up) {
  285. this.thrustAnim.visible = true;
  286. if (this.keys.sprint)
  287. this.thrustSound.volume = 1;
  288. else
  289. this.thrustSound.volume = 0.5;
  290. } else {
  291. this.thrustAnim.visible = false;
  292. this.thrustSound.volume = 0;
  293. }
  294. }
  295. despawn() {
  296. this.game.animate(new Animation({
  297. img: PlayerImgs.despawn,
  298. x: this.pos.x,
  299. y: this.pos.y,
  300. width: 64,
  301. height: 64,
  302. dwidth: 256,
  303. dheight: 256,
  304. offsetX: -128,
  305. offsetY: -128,
  306. wsteps: 5,
  307. hsteps: 5
  308. }));
  309. this.thrustAnim.visible = false;
  310. this.thrustAnim.loop = false;
  311. this.game.playSound(PlayerSounds.despawn, this.pos);
  312. }
  313. }
  314. function createEntity(obj, game) {
  315. if (obj.type == "player") {
  316. return new Player(obj.pos.x, obj.pos.y, obj.id, obj.rot, game);
  317. } else if (obj.type == "bullet") {
  318. return new Bullet(obj.pos.x, obj.pos.y, obj.vel, obj.id, obj.ownerId, game);
  319. } else {
  320. console.log("Unknown entity type: "+obj.type);
  321. return false;
  322. }
  323. }
  324. export default class Game {
  325. constructor(sock, canvas) {
  326. this.sock = sock;
  327. this.canvas = canvas;
  328. this.ctx = canvas.getContext("2d");
  329. this.id = null;
  330. this.camera = new Vec2(0, 0);
  331. this.raf = null;
  332. this.prevTime = new Date().getTime();
  333. this.player = null;
  334. this.onloss = function(){};
  335. this.shake = 0;
  336. this.shakedec = 0.5;
  337. this.keymap = [];
  338. this.keymap[87] = "up";
  339. this.keymap[83] = "down";
  340. this.keymap[65] = "left";
  341. this.keymap[68] = "right";
  342. this.keymap[32] = "shoot";
  343. this.keymap[16] = "sprint";
  344. this.entities = [];
  345. this.animations = [];
  346. sock.on("ready", () => {
  347. sock.send("get_id", {}, (err, res) => {
  348. this.id = res.id;
  349. });
  350. });
  351. sock.on("set", (msg) => {
  352. msg.forEach((m) => {
  353. if (!this.entities[m.id]) {
  354. let ent = createEntity(m, this);
  355. if (ent)
  356. this.entities[m.id] = ent;
  357. } else {
  358. this.entities[m.id].set(m);
  359. }
  360. });
  361. });
  362. sock.on("despawn", (msg) => {
  363. if (!this.entities[msg.id])
  364. return;
  365. this.entities[msg.id].despawn();
  366. delete this.entities[msg.id];
  367. if (msg.id == this.id) {
  368. this.screenShake(400);
  369. setTimeout(() => {
  370. this.stop();
  371. this.onloss();
  372. }, 1200);
  373. }
  374. });
  375. window.addEventListener("keydown", (evt) => {
  376. if (this.keymap[evt.keyCode]) {
  377. evt.preventDefault();
  378. evt.stopPropagation();
  379. this.sock.send("keydown", {
  380. key: this.keymap[evt.keyCode]
  381. });
  382. }
  383. });
  384. window.addEventListener("keyup", (evt) => {
  385. if (this.keymap[evt.keyCode]) {
  386. this.sock.send("keyup", {
  387. key: this.keymap[evt.keyCode]
  388. });
  389. }
  390. });
  391. this.update();
  392. }
  393. update() {
  394. let dt = new Date().getTime() - this.prevTime;
  395. this.prevTime = new Date().getTime();
  396. this.canvas.width = window.innerWidth;
  397. this.canvas.height = window.innerHeight;
  398. let player = this.entities[this.id];
  399. if (player) {
  400. this.camera.set(
  401. player.pos.x - (window.innerWidth / 2),
  402. player.pos.y - (window.innerHeight / 2)
  403. );
  404. }
  405. let shakeOffset = new Vec2(0, 0);
  406. if (this.shake > 0) {
  407. shakeOffset.set(
  408. (Math.random() - 0.5) * this.shake,
  409. (Math.random() - 0.5) * this.shake
  410. );
  411. this.shake -= dt * this.shakedec;
  412. } else {
  413. shakeOffset.set(0, 0);
  414. }
  415. let cam = this.camera.clone().add(shakeOffset);
  416. background(this.ctx, this.camera, shakeOffset);
  417. this.ctx.translate(-cam.x, -cam.y);
  418. this.entities.forEach((ent) => {
  419. this.ctx.save();
  420. this.ctx.translate(ent.pos.x, ent.pos.y);
  421. ent.draw(this.ctx, this.id);
  422. this.ctx.restore();
  423. ent.update(dt);
  424. });
  425. this.animations.forEach((a) => {
  426. this.ctx.save();
  427. a.animate(this.ctx);
  428. this.ctx.restore();
  429. });
  430. this.ctx.translate(cam.x, cam.y);
  431. this.raf = window.requestAnimationFrame(this.update.bind(this));
  432. }
  433. stop() {
  434. window.cancelAnimationFrame(this.raf);
  435. }
  436. screenShake(n) {
  437. if (this.shake < n)
  438. this.shake = n;
  439. }
  440. animate(animation) {
  441. let i = this.animations.length;
  442. this.animations.push(animation);
  443. animation.onend = () => {
  444. delete this.animations[i];
  445. };
  446. }
  447. playSound(url, pos) {
  448. let player = this.entities[this.id];
  449. let dist = player.pos.clone().sub(pos);
  450. console.log(dist, dist.length());
  451. let sound = document.createElement("audio");
  452. sound.src = url;
  453. sound.volume = Math.max(1 - (dist.length() / 1000), 0);
  454. sound.play();
  455. }
  456. }