unibutton/js/index.js
2024-11-25 14:14:20 -05:00

93 lines
No EOL
1.9 KiB
JavaScript

const cs = 1024;
const assets = [
'assets/player.svg',
'assets/head.svg',
];
function Game() {
let canvas = document.querySelector("#canvas");
let ctx = canvas.getContext("2d");
let camera = { x: 0, y: 0 };
let pos = { x: 0, y: 0 };
let vel = { x: 0, y: 0 };
canvas.width = canvas.height = cs;
this.canvas = canvas;
this.ctx = ctx;
this.camera = camera;
this.pos = pos;
this.vel = vel;
this.rot = 0;
this.dir = 1;
this.ticks = 1;
this.assetsIn = {
};
for (let asset in assets) {
this.assetsIn[asset] = new Image();
this.assetsIn[asset].src = assets[asset];
}
}
Game.prototype.main = function () {
this.pos.x += this.vel.x;
this.pos.y += this.vel.y;
this.vel.x *= 0.9;
this.vel.y *= 0.9;
this.rot += 0.08 * this.dir;
this.rot = this.rot % (Math.PI * 10);
this.ticks++;
this.camera.x = -this.pos.x * 0.1 + this.camera.x * 0.9;
this.camera.y = -this.pos.y * 0.1 + this.camera.y * 0.9;
}
// todo: move into its own file
Game.prototype.render = function () {
let { ctx, assetsIn, pos, camera } = this;
ctx.clearRect(0, 0, cs, cs);
ctx.save();
ctx.translate(camera.x + cs / 2, camera.y + cs / 2);
ctx.save();
ctx.translate(pos.x, pos.y);
ctx.rotate(this.rot);
ctx.drawImage(assetsIn[1], -64 / 2, -128, 64, 128);
ctx.restore();
ctx.drawImage(assetsIn[0], pos.x - 64 / 2, pos.y - 64 / 2, 64, 64);
ctx.restore();
}
Game.prototype.click = function () {
let { rot } = this;
if (this.ticks < 10) {
this.dir *= -1;
}
this.vel.x += Math.sin(rot) * 25;
this.vel.y -= Math.cos(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();