GrandTabernacleAutoVI/public_html/js/input.js
2023-12-12 13:53:55 +01:00

90 lines
No EOL
2.8 KiB
JavaScript

class Input {
constructor(idCanvas) {
this.keysDown = new Set()
this.dir = 0;
this.canvas = document.getElementById(idCanvas);
this.canvas.addEventListener("click", (e) => {
if(player==null || bullets==null){
return;
}
let bounds = this.canvas.getBoundingClientRect();
let mouseX = (e.clientX - bounds.x)*this.canvas.width/bounds.width;
let mouseY = (e.clientY - bounds.y)*this.canvas.height/bounds.height;
let dx = mouseX-player.x;
let dy = mouseY-player.y;
let norm = Math.sqrt(dx*dx+dy*dy);
let b = new Bullet(player.x,player.y,player.z,dx/norm,dy/norm,player.id);
bullets.push(b);
net.newBullet(b.x,b.y,b.z,b.dx,b.dy,b.parentId);
});
window.addEventListener("keydown", (e)=>{
//blocks the action of the key (cf. Killian)
if(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.code)) {
e.preventDefault();
}
this.keysDown.add(e.key.toLowerCase())
this.updateDir();
})
window.addEventListener("keyup", (e)=>{
this.keysDown.delete(e.key.toLowerCase())
this.updateDir();
})
}
updateDir(){
if(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)
{
player.changeDirection(this.dir);
net.update(player);
}
}
/*
calculateAngle(playerX, playerY) {
return Math.atan2(this.mouseY - playerY, this.mouseX - playerX);
}
*/
}