I have a function that checks if bullet hits a player, and if so it should remove the bullet and the player that got hit.
I have check_if_bullet_hit_player(bulletRef) function that gets a bullet ref, and the id of the player got shot.
I also have a shoot() function that calls the check_if_bullet_hit_player(bulletRef) for every bullet's movement.
Currently when a bullet hits a player, the bullet disappear, but I can't make the player got hit to disappear also.
I tried the following shoot function:
function shoot(speed=0.5, distance=5, targetX, targetY){
var shoot = setInterval(function() {
check_if_bullet_hit_player(bulletRef).then(player_got_shot_id => {
if (player_got_shot_id != ""){
clearInterval(shoot);
bulletRef.remove();
hitPlayerRef = firebase.database().ref(`players/${player_got_shot_id}`);
hitPlayerRef.once("value").then(function(){
alert("hi");
hitPlayerRef.remove();
})
}
})
})
}
I get alert hi when a player gets hit, and the player that gets hit disappear for a moment, then re-created (which is not what is wanted). I think that the player get re-created because of async, so I tried different methods.
I tried as the following stack overflow's answer, which waits for the ref to return:
function shoot(speed=0.5, distance=5, targetX, targetY){
var shoot = setInterval(function() {
check_if_bullet_hit_player(bulletRef).then(player_got_shot_id => {
if (player_got_shot_id != ""){
clearInterval(shoot);
bulletRef.remove();
await firebase.database().ref(`players/${player_got_shot_id}`).remove();
}
})
})
}
and I get:
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
I tried to wait with then:
function shoot(speed=0.5, distance=5, targetX, targetY){
var shoot = setInterval(function() {
check_if_bullet_hit_player(bulletRef).then(player_got_shot_id => {
if (player_got_shot_id != ""){
clearInterval(shoot);
bulletRef.remove();
hitPlayerRef = firebase.database().ref(`players/${player_got_shot_id}`);
return hitPlayerRef.get(); // HERE we chain the promise
}
}).then(hola => {
hola.remove();
})
})
}
But nothing happens.
How can I make the player got hit to disappear?