42_ft_transcendence/frontend/static/js/api/game/MyPlayer.js

102 lines
2.7 KiB
JavaScript

import { Player } from "./Player.js";
import { Client } from "../Client.js";
import { Game } from "./Game.js";
import { Segment } from "./Segment.js";
class MyPlayer extends Player
{
/**
* @param {Client} client
* @param {Game} game
* @param {Segment} rail
* @param {[Number]} score
* @param {Number} position
*/
constructor(client, game, score, rail, position)
{
super(game, client.me.id, client.me.username, score, rail, position, true);
/**
* @type {Client}
*/
this.client = client;
this.upKeys = [];
this.downKeys = [];
console.log(rail.start.x, rail.stop.x)
if (rail.start.x != rail.stop.x)
{
if (rail.start.x < rail.stop.x)
{
this.upKeys.push("a");
this.downKeys.push("d");
}
else
{
this.upKeys.push("d");
this.downKeys.push("a");
}
}
if (rail.start.y != rail.stop.y)
{
if (rail.start.y < rail.stop.y)
{
this.upKeys.push("w");
this.downKeys.push("s");
}
else
{
this.upKeys.push("s");
this.downKeys.push("w");
}
}
}
/**
* @param {[string]} keys_pressed
*/
update_paddle(keys_pressed)
{
let new_pos = this.position;
keys_pressed.forEach(key => {
if (this.downKeys.includes(key))
new_pos += this.game.config.paddle_speed_per_second_max * this.game.time.deltaTimeSecond();
if (this.upKeys.includes(key))
new_pos -= this.game.config.paddle_speed_per_second_max * this.game.time.deltaTimeSecond();
});
new_pos = Math.max(0 + this.game.config.paddle_ratio / 2, new_pos);
new_pos = Math.min(1 - this.game.config.paddle_ratio / 2, new_pos);
if (this.position === new_pos)
return;
this.position = new_pos;
this.game._send_paddle_position(this.position, this.game.time._current_frame);
}
/**
* @param {Number} new_position
* @param {Number} time
*/
update_pos(new_position, time)
{
let position_verified = new_position;
let time_diff = (this.time._current_frame - time) / 1000;
let sign = this - new_position >= 0 ? 1 : -1;
let distance = Math.abs(this.position - new_position);
let distance_max = time_diff * this.game.config.paddle_speed_per_second_max;
if (distance > distance_max)
position_verified = distance_max * sign;
this.position = position_verified;
}
}
export { MyPlayer };