unibutton/common/player.js
2024-09-29 22:37:33 -04:00

94 lines
No EOL
2.1 KiB
JavaScript

import crypto from "../crypto.js";
function distF(ent, target) {
return ((ent.pos.x - target.pos.x) ** 2) + ((ent.pos.y - target.pos.y) ** 2)
}
function uuidv4() {
return "#000000-000000".replace(/[018]/g, c =>
(+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)
);
}
function Player(you, isPlayer) {
let pos = { x: Math.random() * 1000 - 50, y: Math.random() * 1000 - 50 };
let camera = { x: -pos.x, y: -pos.y };
let vel = { x: 0, y: 0 };
this.camera = camera;
this.pos = pos;
this.vel = vel;
this.rot = 0;
this.dir = 1;
this.ticks = 0;
this.health = 100;
this.you = you || uuidv4();
this.isPlayer = isPlayer;
this.headCount = 0;
}
Player.prototype.bump = function () {
let player = this;
if (player.ticks < 10) {
player.dir *= -1;
}
player.vel.x *= 0.3;
player.vel.y *= 0.3;
player.vel.x += Math.sin(player.rot) * 12;
player.vel.y -= Math.cos(player.rot) * 12;
player.ticks = 0;
}
Player.prototype.handleTick = function (game) {
let { entities, width, height } = game;
let ent = this;
if (ent.health <= 0) return;
ent.pos.x += ent.vel.x;
ent.pos.y += ent.vel.y;
ent.pos.x = Math.max(Math.min(ent.pos.x, width / 2), - width / 2);
ent.pos.y = Math.max(Math.min(ent.pos.y, height / 2), - height / 2);
ent.vel.x *= 0.9;
ent.vel.y *= 0.9;
ent.rot += 0.03 * ent.dir;
ent.rot = ent.rot % (Math.PI * 10);
ent.camera.x = -ent.pos.x * 0.1 + ent.camera.x * 0.9;
ent.camera.y = -ent.pos.y * 0.1 + ent.camera.y * 0.9;
ent.ticks++;
for (let target of entities) {
if (target.you == ent.you) continue;
let dist = distF(ent, target);
let dp = (Math.sin(ent.rot) * (ent.pos.x - target.pos.x))
- (Math.cos(ent.rot) * (ent.pos.y - target.pos.y));
dp /= Math.sqrt(dist + 0.1);
if (Math.sqrt(dist) < 128 && 1 / dp < -0.2) {
target.health--;
if (target.health == 0) {
ent.headCount++;
}
}
}
}
export default Player;