I'm trying to create a function that check if mooving bullet is hitting players.
The code simplified - shoot()
is moving the bullet, and check_if_bullet_hit_player(bulletRef)
gets a bullet ref, and checks if the bullet is hitting any player.
This is my code:
function shoot(){
// ... moving bullet code
const bulletRef = firebase.database().ref(`bullets/${bulletKey}`);
if(check_if_bullet_hit_player(bulletRef)){
alert("player got hit");
bulletRef.remove();
}
}
function check_if_bullet_hit_player(bulletRef){
bulletRef.once("value").then(function(snapshot) {
//for simplicity I just return true - player got hit
return true;
}
}
The code is not triggering the alert()
. After reading this question I think the problem with the asynchrony, but how do I pass parameters to the function, and get the function's return value.
EDIT:
This is the full check_if_bullet_hit_player()
function, which I loop over the players, and checks if the bullet is <0.5
to a player (if so - its count as a hit):
function check_if_bullet_hit_player(bulletRef){
//bulletRef.once("value").then(function(snapshot) {
return bulletRef.get().then(snapshot => {
let bulletX = snapshot.val().x;
let bulletY = snapshot.val().y;
let shooterId = snapshot.val().shooterId;
//loop over players
const allPlayersRef = firebase.database().ref(`players`);
allPlayersRef.once("value", (snapshot) => {
players = snapshot.val() || {};
Object.keys(players).forEach((key) => {
if(getDistance(players[key].x, players[key].y, bulletX, bulletY) < 0.5){
if(players[key].id != shooterId){ //not the shooter
return true;
}
// ...