I have my enemy loaded in a list and when I shoot I check what picked mesh’s name is against said list and I subtract 1 health like :
if(evt.button == 0){
//Play current Weapon’s animation
scene.beginAnimation(player.gunLoadout[currentWeapon].mesh, 0, 100, false);
// Remove ammunition
if(player.gunLoadout[currentWeapon].ammo > 0){
player.gunLoadout[currentWeapon].ammo -= 1;
}// Update HUD hud[2].text = String(player.gunLoadout[player.currentWeapon].ammo); // Destroy camera's ray target in 1000 distance let ray = camera.getForwardRay(10000); let hit = scene.pickWithRay(ray); let model = hit.pickedMesh; // Exempt ground from the be shot at if(hit !== null && model !== null && model.name != "ground"){ for(let i=0; i<enemyList.length ; i++){ if(enemyList[i].name == model.name){ console.log("Target Hit :" + model.name + " Health :" + enemyList[i].health ); enemyList[i].health -= 1; } } } }
Following is the code of my enemy class. I want to destroy the enemy mesh when it detects that its health reaches zero using the destroy method. The thing is I can’t seem to pass the correct health inside the registerBeforeRender part, all I’m doing is passing the health that the object has upon creation, and if I try to use the this.health variable inside the registerBeforeRender “loop” I get that it’s not defined.
export default class Enemy{
constructor(scene, name, mesh){
// Game properties
//this.game = game;
this.scene = scene;
// Enemy properties
this.name = name;
this.mesh = mesh;
this.health = 5;
this.move();
this.destroy();
}
move(){
let mesh = this.mesh;
let scene = this.scene;
let camera = scene.activeCamera;
if(mesh){
this.scene.registerBeforeRender(function(){
// Calculating distances between the enemy and the player
let initVec = mesh.position.clone();
let distVec = BABYLON.Vector3.Distance(camera.position, mesh.position);
let targetVec = camera.position.subtract(initVec);
let targetVecNorm = BABYLON.Vector3.Normalize(targetVec);
// Move enemy towards the player and stops slightly ahead
if(distVec > 10){
distVec -= 0.1;
mesh.translate(targetVecNorm, 0.1, BABYLON.Space.WORLD);
}
// Enemy always faces the player
mesh.lookAt(camera.position, Math.PI);
});
}
}
destroy(){
let mesh = this.mesh;
let health = this.health;
let scene = this.scene;
if(mesh){
this.scene.registerBeforeRender(function(){
console.log("Health:" + health);
if(health == 0){
scene.getMeshByName(mesh.name).dispose();
}
});
}
}
}
It’s obvious that I’m lacking in my JS skills but I know that I’m a bit confused about the context of variables or something. Hope someone skillful can chime in and clear my misunderstandings.