Bullet on shooting game

how to create a bullet in the middle of the screen when i press the fire button . should i use raycasting or something to do

2 Likes

For the most trivial solution - you can indeed just use raycaster whenever player shoots a bullet (either from the gun.getWorldDirection(), or camera.getWorldDirection() - see docs.)

If you’d like a more accurate simulation - ie. one in which a bullet does not travel in a straight line at an infinite speed - consider spawning a physical bullet object, and update it on each frame (that’s also a good solution in case you’d like to implement multiplayer later on) :

const raycaster = new Three.Raycaster();
const raycasterOrigin = new Three.Vector3();
const raycasterDirection = new Three.Vector3();

const bullets = [];
const availableTargets = [
  player1,
  player2,
  // ...
  playerN
];

const shoot = () => {
  const bullet = new Three.Object3D();

  // NOTE Place bullet in scene-scope, so it's movement is independent from the player & the gun
  scene.add(bullet);
  
  // NOTE Place bullet at an initial position and direction, based on where the gun is facing
  gun.getWorldPosition(bullet.position);
  gun.getWorldQuaternion(bullet.quaternion);

  bullets.push(bullet);
};

const updateBullets = () => {
  [...bullets].forEach(bullet => {
    // NOTE Raycast from each bullet and see if it hit any target compatible with the idea of being hit by a bullet
    bullet.getWorldPosition(raycasterOrigin);
    bullet.getWorldDirection(raycasterDirection);

    raycaster.set(raycasterOrigin, raycasterDirection);
    
    const hits = raycaster.intersectObjects(availableTargets, true);
    
    if (hits) {
      const firstHitTarget = hits[0];
      
      // NOTE React to being hit by the bullet in some way, for example:
      // firstHitTarget.onHit();

      // NOTE Remove bullet from the world
      bullet.removeFromParent();
      
      bullets.splice(bullets.indexOf(bullet), 1);
    }

    // NOTE If no target was hit, just travel further, apply gravity to the bullet etc.
    bullet.position.add(raycasterDirection.multiplyScalar(0.1));
  });
};

There’s also plenty of ways to optimise bullets when you have them in the world - in cases like machine or mini-guns you can bundle bullets into groups depending on the rate of fire, you can limit hit-testing only to nearby targets, etc.


This may also be helpful on the way :point_down:

3 Likes

@mjurczyk thank you so much