javascriptthree.js

built dose not shoot straight in three.js


I'm trying to make a shooter in three.js, my bullet shoots right where I turn left and right but when I look up and down it moves up and down but it does not rotate with it.

for (let index=0;index<bulits.length; index+=1){
    if (bulits[index] === undefined) continue;
    if (bulits[index].alive == false){
      bulits.splice(index,1);
      continue;
    }
    bulits[index].position.add(bulits[index].velocity);
    
  }

if (keys.z && gunn){
    let bullit= new THREE.Mesh(
      new THREE.SphereGeometry(0.05,8,8),
      new THREE.MeshBasicMaterial({color:0xffffff})
    );
    bullit.position.copy(swordPosi);
    bullit.alive = true;
    bullit.velocity = new THREE.Vector3(
      -Math.sin(camera.rotation.y),
      Math.sin(swordRotation.z), // the sword is just the name of the guns cannon.js  hit box
      face
    );
    setTimeout(function(){
      bullit.alive = false;
      scene.remove(bullit);
    }, 1000);
    bulits.push(bullit);
    scene.add(bullit);
  }


Solution

  • From reproducing your code, I noticed a shot anomaly. Especially when you use the keys and then the mouse to control it, which causes the bullet's flight trajectory to be reversed. This seems to be what you mean... It seems to be a matter of the bullet's flight, which now depends on the rotation of the camera camera.rotation.y. And it should fly where the camera is facing (where you look at, right?), sort of independently. Notice that your code works but up to a certain point, until you start making crazy turns/spins of the character, then the trajectory breaks down... Try the approach with applyQuaternion(camera.quaternion) which moves bullet exactly where camera is facing, transforms Z-axis vector by the camera rotation.

    I think this content and all channel will be helpful for you, when you doing this type of stuff.

    Try switch your code on this logic, I tried really shaking and jerking camera, but still looks fine.

    if (keys.z && gunn){
    let bullit = new THREE.Mesh(
    new THREE.SphereGeometry(0.05, 8, 8),
    new THREE.MeshBasicMaterial({color: 0xffffff})
    );
    bullit.position.copy(swordPosi);
    bullit.alive = true;
    
    bullit.velocity = new THREE.Vector3(0, 0, -1);
    bullit.velocity.applyQuaternion(camera.quaternion);
    bullit.velocity.multiplyScalar(1);
    
    setTimeout(function(){
    bullit.alive = false;
    scene.remove(bullit);
    }, 1000);
    
    bulits.push(bullit);
    scene.add(bullit);
    }