99 lines
No EOL
2.1 KiB
JavaScript
99 lines
No EOL
2.1 KiB
JavaScript
const cs = 1024;
|
|
const assets = [
|
|
'assets/player.svg',
|
|
'assets/head.svg',
|
|
];
|
|
|
|
function Game() {
|
|
let assetsIn = {};
|
|
|
|
for (let asset in assets) {
|
|
assetsIn[asset] = new Image();
|
|
assetsIn[asset].src = assets[asset];
|
|
}
|
|
|
|
let canvas = document.querySelector("#canvas");
|
|
let player = new Player();
|
|
let entities = [player];
|
|
|
|
for (let i = 0; i < 15; i++) {
|
|
entities.push(new Player())
|
|
}
|
|
|
|
canvas.width = canvas.height = cs;
|
|
|
|
this.canvas = canvas;
|
|
this.ctx = canvas.getContext("2d");
|
|
this.ticks = 1;
|
|
this.assetsIn = assetsIn;
|
|
this.player = player;
|
|
this.entities = entities;
|
|
}
|
|
|
|
Game.prototype.main = function () {
|
|
let { entities } = this;
|
|
|
|
this.ticks++;
|
|
|
|
for (let player of entities) {
|
|
player.pos.x += player.vel.x;
|
|
player.pos.y += player.vel.y;
|
|
|
|
player.vel.x *= 0.8;
|
|
player.vel.y *= 0.8;
|
|
|
|
player.rot += 0.03 * player.dir;
|
|
player.rot = player.rot % (Math.PI * 10);
|
|
|
|
player.camera.x = -player.pos.x * 0.1 + player.camera.x * 0.9;
|
|
player.camera.y = -player.pos.y * 0.1 + player.camera.y * 0.9;
|
|
}
|
|
}
|
|
|
|
// todo: move into its own file
|
|
Game.prototype.render = function () {
|
|
let { ctx, assetsIn, entities, player } = this;
|
|
|
|
ctx.clearRect(0, 0, cs, cs);
|
|
|
|
ctx.save();
|
|
|
|
ctx.translate(player.camera.x + cs / 2, player.camera.y + cs / 2);
|
|
|
|
for (let ent of entities) {
|
|
ctx.save();
|
|
|
|
ctx.translate(ent.pos.x, ent.pos.y);
|
|
ctx.rotate(ent.rot);
|
|
ctx.drawImage(assetsIn[1], -64 / 2, -128, 64, 128);
|
|
|
|
ctx.restore();
|
|
|
|
ctx.drawImage(assetsIn[0], ent.pos.x - 64 / 2, ent.pos.y - 64 / 2, 64, 64);
|
|
}
|
|
|
|
ctx.restore();
|
|
}
|
|
|
|
Game.prototype.click = function () {
|
|
let { player } = this;
|
|
|
|
if (this.ticks < 10) {
|
|
player.dir *= -1;
|
|
}
|
|
|
|
player.vel.x *= 0.6;
|
|
player.vel.y *= 0.6;
|
|
|
|
player.vel.x += Math.sin(player.rot) * 25;
|
|
player.vel.y -= Math.cos(player.rot) * 25;
|
|
|
|
this.ticks = 0;
|
|
}
|
|
|
|
var game = new Game();
|
|
|
|
setInterval(function () { game.main() }, 1000 / 60);
|
|
setInterval(function () { game.render() }, 1000 / 60);
|
|
|
|
game.canvas.onclick = () => game.click(); |