GrandTabernacleAutoVI/public_html/js/input.js
2023-12-07 22:31:50 +01:00

103 lines
No EOL
3.3 KiB
JavaScript

class Input {
constructor(id, net,renderer, sound) {
this.keysDown = new Set()
this.dir = 0;
this.player=null;
this.bullets=null;
this.canvas = document.getElementById(id);
this.renderer=renderer;
this.mouseX = 0
this.mouseY = 0
this.network = net
// Event listener pour la position de la souris
this.canvas.addEventListener("mousemove", this.handleMouseMove.bind(this));
this.canvas.addEventListener("click", (e) => {
if(this.player==null || this.bullets==null){
return;
}
if(this.player.x>=2000 && this.player.y>=2000 && this.mouseX<2000 && this.mouseY<2000) {
this.mouseX=this.mouseX+2000;
this.mouseY=this.mouseY+2000;
}
let dx = this.mouseX-this.player.x;
let dy = this.mouseY-this.player.y;
let norm = Math.sqrt(dx*dx+dy*dy);
let b = new Bullet(this.player.x,this.player.y,dx/norm,dy/norm,this.player.id, sound);
this.bullets.push(b);
this.renderer.addBullet(b);
this.network.newBullet(b.x,b.y,b.dx,b.dy,b.parentId);
});
window.addEventListener("keydown", (e)=>{
this.keysDown.add(e.key.toLowerCase())
this.updateDir();
})
window.addEventListener("keyup", (e)=>{
this.keysDown.delete(e.key.toLowerCase())
this.updateDir();
})
}
updateDir(){
if(this.player==null)
return;
let oldDir=this.dir;
this.dir=0;
if(this.keysDown.has('z') || this.keysDown.has('arrowup')){
if(this.keysDown.has('d') || this.keysDown.has('arrowright')){
this.dir = 2;
}else if(this.keysDown.has('s') || this.keysDown.has('arrowdown')){
this.dir = 0;
}else if(this.keysDown.has('q') || this.keysDown.has('arrowleft')){
this.dir = 8;
}else{
this.dir = 1;
}
}else if(this.keysDown.has('d') || this.keysDown.has('arrowright')){
if(this.keysDown.has('s') || this.keysDown.has('arrowdown')){
this.dir = 4;
}else if(this.keysDown.has('q') || this.keysDown.has('arrowleft')){
this.dir = 0;
}else{
this.dir = 3;
}
}else if(this.keysDown.has('s') || this.keysDown.has('arrowdown')){
if(this.keysDown.has('q') || this.keysDown.has('arrowLeft')){
this.dir = 6;
}else{
this.dir = 5;
}
}else if(this.keysDown.has('q') || this.keysDown.has('arrowleft')){
this.dir = 7;
}
if(oldDir!=this.dir)
{
this.player.changeDirection(this.dir);
this.network.update(this.player);
}
}
get getDirection() {
return this.dir;
}
handleMouseMove(event) {
let mX = event.clientX - this.canvas.getBoundingClientRect().left;
let mY = event.clientY - this.canvas.getBoundingClientRect().top;
this.mouseX = mX;
this.mouseY = mY;
}
calculateAngle(playerX, playerY) {
return Math.atan2(this.mouseY - playerY, this.mouseX - playerX);
}
}