unibutton/common/player.js
2024-10-03 05:16:40 -04:00

110 lines
No EOL
2.7 KiB
JavaScript

import { distF, uuidv4 } from './util.js'
class Player {
constructor(you, isPlayer, game = false) {
let pos = { x: (Math.random() - 0.5) * (game ? game.width : 1000), y:(Math.random() - 0.5) * (game ? game.height : 1000) };
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;
this.type = 'Player';
this.isMenu = false;
this.r = 1;
this.isYou = false;
this.serverProps = [
'type', 'camera', 'pos', 'vel', 'rot', 'dir', 'ticks', 'health', 'you', 'isPlayer', 'headCount', 'isMenu', 'r', 'isYou'
];
this.legalProps = [
'vel', 'dir', 'camera', 'ticks', 'isMenu', 'r'
];
}
bump() {
let player = this;
if (player.ticks < 15) {
player.dir *= -1;
}
console.log(player.ticks)
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;
}
handleTick(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++;
let velness = Math.sqrt(ent.vel.x ** 2 + ent.vel.y ** 2);
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) {
if (target.type == 'NPC' && velness > 0.2) {
ent.isMenu = true;
ent.rot = 1.2;
}
if (target.immortal) continue;
target.health--;
if (target.health == 0) {
ent.headCount++;
}
}
}
}
}
export default Player;