GrandTabernacleAutoVI/public_html/js/input.js
2023-12-09 13:19:04 +01:00

94 lines
No EOL
2.9 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;
if(player.x>=2000 && player.y>=2000) {
mouseX+=2000;
mouseY+=2000;
}
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,dx/norm,dy/norm,player.id);
bullets.push(b);
net.newBullet(b.x,b.y,b.dx,b.dy,b.parentId);
});
window.addEventListener("keydown", (e)=>{
if(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].indexOf(e.code) > -1) {
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);
}
*/
}