The trajectory in three.js is not always accurate

As I work on creating a shooter in three.js, I've encountered an issue. When I change my aim left and right, the bullet fires in the correct direction. However, when I adjust my aim up and down, the bullet moves in those respective directions but doesn't rotate accordingly.

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);
  }

Answer №1

Upon analyzing your code, I noticed a slight anomaly. Specifically, when using both the keys and the mouse to control it, there is a reversal in the trajectory of the bullet's flight. It appears that the issue lies in the bullet's flight path, which is currently dependent on the rotation of the camera, camera.rotation.y. The bullet should instead travel in the direction the camera is facing (the direction you are looking at), somewhat independently. While your current code functions adequately, it struggles when the character performs abrupt and extreme movements, causing the trajectory to destabilize. Consider implementing the use of

applyQuaternion(camera.quaternion)
, which will accurately position the bullet in the direction the camera is facing by transforming the Z-axis vector according to the camera's rotation.

I believe that watching this informative video and channel will provide valuable insights for you as you work on similar tasks.

Try adapting your code to this logical approach; even after vigorously shaking and moving the camera, the results remained satisfactory.

if (keys.z && gunn){
let bullet = new THREE.Mesh(
new THREE.SphereGeometry(0.05, 8, 8),
new THREE.MeshBasicMaterial({color: 0xffffff})
);
bullet.position.copy(swordPosition);
bullet.alive = true;

bullet.velocity = new THREE.Vector3(0, 0, -1);
bullet.velocity.applyQuaternion(camera.quaternion);
bullet.velocity.multiplyScalar(1);

setTimeout(function(){
bullet.alive = false;
scene.remove(bullet);
}, 1000);

bullets.push(bullet);
scene.add(bullet);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we effectively share code between server-side and client-side in Isomorphic ReactJS applications?

For a small test, I am using express.js and react.js. Below you can find my react code: views/Todo.jsx, var React = require('react'); var TodoApp = React.createClass({ getInitialState: function() { return { counter: 0 ...

When using jQuery Ajax, only pass the query string if it is defined and not empty

Using jquery and ajax to communicate with a CMS API, I am constructing a query string to fetch data: region = typeof region !== 'undefined' ? 'region='+region : ''; centre = typeof centre !== 'undefined' ? 'cen ...

The error message "TypeError: Router.use() expects a middleware function, but received a [type of function]" is a common occurrence in FeathersJS

Struggling to bind a method to my /userAuthenticationInfo route, I've made several adjustments in my code based on other posts related to this issue but still unable to make it work. I am using feathersJS's express implementation, and even with e ...

Encountering an issue with React and material-ui-pickers date-io Jalaali Utils: receiving a TypeError stating that utils.getDayText is not recognized as

This issue is different from what was discussed in https://github.com/mui-org/material-ui-pickers/issues/1440 because I am not facing any problems with the original implementation. Referencing the link provided here , I have utilized JalaliUtils from @da ...

A guide on transferring and transforming text data on the server

While I have a basic understanding of php, ajax, and javascript (including jQuery), I am still a beginner and could use some assistance with connecting the dots for this simple task: My goal is to allow the user to input text (for example: "I saw the sun, ...

JavaScript can be used to activate the onclick event

Is there a way to disable and then re-enable all buttons that share the same class name? I attempted the following code without success: let buttons = document.getElementsByClassName("btn-st"); for (let i = 0; i < buttons.length; i++) { b ...

Understanding the implementation of options within dataTables that have been initialized with an aaData JavaScript array

When initializing my datatable, I used an aaData object and specific options like so: $('#dataTable').dataTable(dataTableObj, { "bPaginate": false, "bLengthChange": false, "bFilter": true, "bSort": false, "bInfo": false, ...

Problem encountered when attempting to post to a node/express endpoint

It has been a while since I last used JQuery/Ajax instead of axios to connect to an endpoint, am i making any mistakes here? var express = require('express'); var app = express() var bodyParser = require('body-parser'); var path = re ...

Async/await is restricted when utilizing serverActions within the Client component in next.js

Attempting to implement an infinite scroll feature in next.js, I am working on invoking my serverAction to load more data by using async/await to handle the API call and retrieve the response. Encountering an issue: "async/await is not yet supported ...

Creating a JSON Array from a PHP Array with json_encode()

I have used the built-in json_encode() function to encode an Array that I created. I am in need of formatting it into an Array of Arrays as shown below: { "status": "success", "data": [ { "Info": "A", "hasil": "AA" }, { " ...

Using JavaScript to assign function arguments based on arbitrary object values

I am facing a challenge with a collection of arbitrary functions and a method that takes a function name along with an object or array of parameters to call the respective function. The issue arises from the varying number of inputs in these functions, som ...

Pass an array of links from the parent component to the child component in Vue in order to generate a dynamic

I am currently working on building a menu using vue.js. My setup includes 2 components - Navigation and NavLink. To populate the menu, I have created an array of links in the App.vue file and passed it as props to the Navigation component. Within the Navig ...

Blender Mesh Not Visible in Three.js

After creating a mesh in Blender, I attempted to use it in three.js. Although the file is being loaded according to the event log, all I see is a black screen. How can I ensure that the mesh actually appears on the screen? import * as THREE from 'thre ...

Locate and modify a specific element within an array of objects

Currently, I am working with an array that looks like this: arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]. However, I need to add a condition to the array. If ...

Employing useEffect within Material-UI tabs to conceal the third tab

At the page's initial load, I want to hide the first two tabs. The third tab should be visible with its content displayed right away. Currently, I can only see the content after clicking on the third tab. To troubleshoot this issue, I attempted to use ...

Encountering a roadblock while trying to work with AngularJS Material radio buttons

In one of my projects, I have implemented a polling system where users can choose a question from a list and then proceed to the options page. On the options page, users can select their answer choices and submit their responses. The results are then displ ...

Modifying the color of an individual object in THREE.js: Step-by-step guide

I am currently working on editing a program that uses Three.js and Tween.js. Despite my efforts to find a solution both here and online, I have not been successful. The program involves creating multiple objects (cones) using THREE.Mesh, with a script that ...

What is the process for separating static methods into their own file and properly exporting them using ES6?

After exploring how to split up class files when instance and static methods become too large, a question was raised on Stack Overflow. The focus shifted to finding solutions for static factory functions as well. The original inquiry provided a workaround ...

React: Implementing Material-UI Typography with custom inline spacing

Take a look at this code snippet: <Typography className={classes.welcomeMessage} variant="h1"> A <span className={classes.redText}>smart nation </span> approach to <span className={classes.redText} ...

Surprising message found within a pug file containing javascript code

I'm encountering an issue that I am unsure how to resolve. I am relatively new to working with pug files and the error message below is appearing: Error: /home/nobin/jadeApp/views/show_message.pug:9:33 7| else 8| h3 New person, ...