unibutton/js/index.js

93 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-11-25 14:14:20 -05:00
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;
2024-11-25 14:14:20 -05:00
this.dir = 1;
this.ticks = 1;
2024-11-25 14:14:20 -05:00
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;
2024-11-25 14:14:20 -05:00
this.rot += 0.08 * this.dir;
2024-11-25 14:14:20 -05:00
this.rot = this.rot % (Math.PI * 10);
2024-11-25 14:14:20 -05:00
this.ticks++;
2024-11-25 14:14:20 -05:00
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();
2024-11-25 14:14:20 -05:00
ctx.translate(camera.x + cs / 2, camera.y + cs / 2);
2024-11-25 14:14:20 -05:00
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;
2024-11-25 14:14:20 -05:00
if (this.ticks < 10) {
this.dir *= -1;
}
2024-11-25 14:14:20 -05:00
this.vel.x += Math.sin(rot) * 25;
this.vel.y -= Math.cos(rot) * 25;
2024-11-25 14:14:20 -05:00
this.ticks = 0;
2024-11-25 14:14:20 -05:00
}
var game = new Game();
setInterval(function () { game.main() }, 1000 / 60);
setInterval(function () { game.render() }, 1000 / 60);
game.canvas.onclick = () => game.click();