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 9.5KB

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