Making bullets come out of a weapon

Hi! I’m trying to make bullet objects originate from the player’s weapon in my first person shooter. Is there some way to properly modify the vector being copied in this function to do so?

Here the bullet is created, assigned the position of the player’s camera, the cameras direction, and given a speed.

function addBullet(position, speed, direction) {

  let particle = new THREE.Mesh(new THREE.CubeGeometry(2,2,2), new THREE.MeshNormalMaterial({visible: true}));

  particle.position.copy(position);
  
  particle.quaternion.copy(direction);
       
  particle.position.set( position.x + 3 , position.y + 0.10, position.z + 0.1 );

  particle.scale.x = particle.scale.y = .5;

  bullets.push(new bullet(particle, speed, false));

  glScene.scene.add(particle);

}

AddBullet(glScene.camera.position, speed, glScene.camera.quaternion);

You see I tried to simply increase the x value on the position vector however this only works for a small portion of the direction the player is facing.

Please let me know if I provided insufficient code.

1 Like

is your weapon an object3d?
If so, copy the position of that and copy that to the start position of your bullet.
Also use the weapon quaternion instead of the camera so that your bullet takes the direction of the weapon. Considering the direction of your weapon is useful only if it changes. Such as usually in a VR fps. Other wise copy the camera quaternion to your bullet.

1 Like

Yes, so what I’ve done is just added the loaded model to the camera.

loader.load(weapon, function (gltf) {
      model = gltf.scene;
      model.position.y = -13;
      model.rotation.y = THREE.Math.degToRad(180);           
      glScene.camera.add(model);  
  });

How do I access the children of the camera to get the position of the weapon object?

Edit: actually this wont work considering the way I’ve created the model relative to the FOV of the camera. to where I only need to position it along the Y axis when loading it in. Is it not possible to set the position of the bullet to the right of the camera’s direction as it is added to the scene?

if a reference to your weapon can be accessed in the global scope, you should be able to get its world position and quaternion.

const objectsWorldPosition = new THREE.Vector3()
object.getWorldPosition(objectsWorldPosition)

const objectsWorldQuaternion = new THREE.Quaternion
object.getWorldQuaternion(objectsWorldQuaternion)

Or,
do a console.dir on your camera and your weapon mesh is probably at camera.children[0]

eg,

const weaponPos = new THREE.Vector3()
camera.children[0].getWorldPosition(weaponPos)

const weaponQuat = new THREE.Quaternion
camera.children[0].getWorldQuaternion(weaponQuat)

Note, I haven’t tested this code, but it is something like this,