How to attach a weapon(Gun) to a character bone?

I’m trying to attach a gun to a character but can’t find a way to access the character bone. Is there a sample project I can have a look at or a code snippet?

I have already tried the following code:

bone = this.entity.findByName(‘BoneName’);
And:
bone.addChild(gunEntity);

But then I got the following error.
[playcanvas-stable.js:7951]: Error: GraphNode is already parented

I also tried reparenting the weapon but can’t see the weapon in the character’s hand.
this.gun.reparent(this.rightHandBone);

But the shoot logic is working fine though!

What to do!!!

Any help would be appreciated. :smile:

1 Like

The reparenting code you are using is correct. A few things to check:

  • this.rightHandBone is not null
  • the scale is not zero/very small
  • the gun entity is enabled

You could try attaching a sphere entity instead and see if that works.

Also check that the weapon isn’t currently translated a massive amount in some direction. A .setLocalPosition(pc.Vec3.ZERO) would ensure that it is right at the bone.

1 Like

Actually looks like the bones has scales applied, so the resulting model was very small.

Added this code to re-scale it:

var scale = this.entity.getWorldTransform().getScale();
this.entity.setLocalScale(1/scale.x, 1/scale.y, 1/scale.z);
1 Like

Thanks guys, looks like scaling was the issue, re-scaling the weapon as suggested by dave fixed the problem. Looks good and working as expected. :smile: