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

1 Like

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 = [
  // ...

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

  // NOTE Place bullet in scene-scope, so it's movement is independent from the player & the gun
  // NOTE Place bullet at an initial position and direction, based on where the gun is facing


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

    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
      bullets.splice(bullets.indexOf(bullet), 1);

    // NOTE If no target was hit, just travel further, apply gravity to the bullet etc.

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:


@mjurczyk thank you so much