Hi! I have code that spawns a bullet from the player’s gun every time my animation handler detects an animation event from Spine2D. Which would be better, programmatically generating the bullet every time the event fires or copying a prefab and adding it as a child to root?
The firing animation is pretty fast since the character uses an SMG, so the event gets fired every 6ms or so.
For reference, this is what is called every time the animation handler detects the animation event:
Player.prototype.onPlayerFire = function () {
var mouseWorldPos = this.mouseWorldPos;
var bulletBaseDamage = this.bulletBaseDamage;
if ( this.ammo <= 0 ) {
this.currentState.shooting = false;
this.onDryFire();
var anim = this.entity.spine.state.setAnimationWith(2,this.waitUpperAnimation,true);
anim.mixDuration = 0.2;
return;
}
var newBullet = new pc.Entity();
// newBullet.setLocalPosition(this.entity.localPosition.x + this.skeletonArms.worldX,this.entity.localPosition.y + this.skeletonArms.worldY,0);
newBullet.setLocalPosition(this.entity.localPosition.x + this.skeletonBullet.worldX,this.entity.localPosition.y + this.skeletonBullet.worldY,0);
newBullet.setLocalScale(0.1,0.1,0.1);
newBullet.addComponent("script");
newBullet.script.create("bullet", {
attributes: {
bulletBaseDamage: bulletBaseDamage
}
});
newBullet.addComponent("model",{
type: "sphere"
});
newBullet.addComponent("collision",{
type: "sphere",
radius: 0.1
});
newBullet.addComponent("rigidbody",{
type: "dynamic",
mass: 5
});
newBullet.rigidbody.body.setCcdSweptSphereRadius(0.01);
newBullet.rigidbody.linearFactor.set(1,1,0);
newBullet.tags.add("bullet");
if ( this.currentState.lookingRight ) {
newBullet.setEulerAngles(this.angle*2,-90,0);
} else {
newBullet.setEulerAngles(this.angle*2,90,0);
}
newBullet.rotate(0,0,pc.math.random(-this.bulletSpread,this.bulletSpread));
var bulletDirection = newBullet.forward;
newBullet.rigidbody.linearVelocity = bulletDirection.scale(30);
this.app.root.addChild(newBullet);
var gunFire = this.entity.sound.play("gunfire");
gunFire.pitch = 1 + pc.math.random(0.9,1.1);
this.ammo -= 1;
this.hudUI.fire("player:fire",this.ammo.toString());
};
Project: https://playcanvas.com/editor/scene/874238
Game: https://launch.playcanvas.com/874238