Hi,
Recently I trying to create a shooting prototype and I get stuck with the health bar. I got a wall which attached health.js
and also my player also attached with health.js
I using healthEntity = this.entity.findByPath('health');
to get the health bar of the object that I hit. When I hit the wall, it will deducted my player’s health bar instead of the health bar of the wall.
The screenshot when I launch the game:
Below is health.js
:
var Health = pc.createScript('health');
Health.attributes.add('ehealth',{ type: 'number',
default: 100,});
var Shoot;
var textElement;
var healthEntity;
// initialize code called once per entity
Health.prototype.initialize = function() {
Shoot=false;
var self=this;
this.entity.collision.on('collisionstart', this.onCollisionStart, this);
this.entity.collision.on('collisionend', this.onCollisionEnd, this);
this.camera = this.app.root.findByName('Camera');
//All the object or player with health bar got a healthtxt and an entity call health
textElement = this.entity.findByPath('3D Screen/healthtxt');
healthEntity = this.entity.findByPath('health'); // we're searching inside the entity
this.takeDamage = 0;
textElement.element.text=this.ehealth;
};
// update code called every frame
Health.prototype.update = function(dt) {
// this.entity.setRotation(this.camera.getRotation());
var scale = new pc.Vec3().copy(healthEntity.getLocalScale()); // store the scale inside a new vec3 (scale is a vec3)
if (Shoot) {
scale.x = pc.math.lerp(scale.x, 0, 0.25); // SCALE DOWN
this.ehealth-=5;
console.log(this.ehealth);
textElement.element.text=this.ehealth;
}
healthEntity.setLocalScale(scale);
if (scale.x < 0.01) {
scale.x = 0;
this.entity.destroy();
}
healthEntity.setLocalScale(scale);
};
Health.prototype.onCollisionStart=function(result){
if(result.other.tags.has('bullet')){
Shoot=true;
}
};
Health.prototype.onCollisionEnd=function(other){
if(other){
Shoot=false;
}
};
// swap method called for script hot-reloading
// inherit your script state here
// Health.prototype.swap = function(old) { };
// to learn more about script anatomy, please read:
// http://developer.playcanvas.com/en/user-manual/scripting/
Sincerely,
Elliot.