Try incorporating "vector.applyQuaternion" or a similar method in your code within ammo.js

I'm eager to develop a virtual reality shooting game for browsers, utilizing Three.js and Ammo.js for the physics engine and rigid bodies. Although I've successfully set up the VR headset, controllers, and loaded models, I encountered an issue with the bullets not firing correctly from the gun as intended. In a previous attempt without using Ammo.js, I relied on "vector.applyQuaternion" from the Three.js documentation, which effectively launched the bullets from the gun's top. However, I am struggling to find a similar solution while incorporating ammo.js into the project.

Code snippet without ammo.js

...  function handleController( controller ) {

           if ( controller1.userData.isSelecting ) {

            bullet1.position.set( controller1.position.x , controller1.position.y + 0.018 , controller1.position.z -0.01);
            bullet1.userData.velocity.x = 0;
            bullet1.userData.velocity.y = 10;
            bullet1.userData.velocity.z = 10;
            bullet1.userData.velocity.applyQuaternion( controller1.quaternion );
            scene.add(bullet1);

           }

            if ( controller2.userData.isSelecting ) {

            bullet2.position.set( controller2.position.x  , controller2.position.y + 0.018 , controller2.position.z -0.01 );
            bullet2.userData.velocity.x = 0;
            bullet2.userData.velocity.y = 10;
            bullet2.userData.velocity.z = 10;
            bullet2.userData.velocity.applyQuaternion( controller2.quaternion );
            scene.add(bullet2);

           }

      } ...

    function render() {
        handleController( controller1 );
        handleController( controller2 );

        var delta = clock.getDelta()
        bullet1.position.x -= bullet1.userData.velocity.x *  delta;
        bullet1.position.y -= bullet1.userData.velocity.y *  delta;
        bullet1.position.z -= bullet1.userData.velocity.z *  delta;

        bullet2.position.x -= bullet2.userData.velocity.x *  delta;
        bullet2.position.y -= bullet2.userData.velocity.y *  delta;
        bullet2.position.z -= bullet2.userData.velocity.z *  delta;

        renderer.render( scene, camera ); 
    } 

Code with ammo.js

... // The code provided in this section focuses on creating rigid bodies for bullets using Ammo.js

The outcome is that the bullets are generated but exhibit movement solely along the z-axis. Specifically, the velocity of bullet2 varies upon moving the controller along the x-axis, indicating that the bullets are solely restricted to the z-axis motion. While bullet1 aligns with movements across all axes, it fails to follow the controller's rotation. Furthermore, attempting to incorporate quaternion rotation like in the previous example results in an error due to the absence of LinearVelocity property. Instead, only getLinearVelocity and setLinearVelocity methods are supported in ammo.js.

Answer №1

After reviewing various ammo versions, it appears that your implementation of setLinearVelocity() may not be accurate. The btVector3 constructor should only accept x, y, and z values. You can calculate this using ThreeJS math in a similar manner to what you have done elsewhere (selecting the magnitude and rotating the vector3 by the controller's quaternion). This adjustment should help resolve any issues you are encountering.

It is worth considering why your bullets need to be physically simulated in the first place. Most shooting games opt for a simpler approach of visually updating the bullet's progress while monitoring for collisions with players or walls. If you want to incorporate gravity effects, you could apply a slight vertical drop each frame. For ricochet effects, use the normal of the surface upon impact to modify the velocity. Keep in mind that the Ammo engine excels at scenarios like grenade bouncing due to its ability to handle complex and unpredictable interactions.

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

Uncovering the Android tablet browser: A guide

I have implemented the code below to detect mobile/tablet browsers. function isMobile() { var index = navigator.appVersion.indexOf("Mobile"); return (index > -1); } Although it works well for desktop browsers and iOS devices (iPhon ...

Using a variety of objects in TypeScript arrays

How to effectively implement a superior class in TypeScript for an array containing diverse objects that inherit from the same class, without triggering errors? This is my attempt: interface IVehicle{ modelName: string } interface ICar extends IVehi ...

Encountering a sudden problem while running gulp build due to a node_module - Surprising occurrence of Unexpected

Encountering an unexpected issue while running a gulp build process for a web app that I am struggling to resolve. The problem did not exist on the evening of 25/01/2019, but when attempting to execute the gulp build process this morning (30/01/2019), an ...

How can I change the background color of a parent div when hovering over a child element using JavaScript

I am working on a task that involves three colored boxes within a div, each with a different color. The goal is to change the background-color of the parent div to match the color of the box being hovered over. CSS: .t1_colors { float: left; wid ...

Center your attention on an AngularJS-created input element

I'm currently working on a todo list project using AngularJS and I am wondering if there is a method to automatically focus on an input box after creating it by clicking on a button. As of now, the save function in my controller looks like this: $sc ...

Explore a JSON array within another JSON array

Here is a JSON format that I have: { "Project [id=1, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd ]" : [ {"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26"}, {"id":2,"title":"sss ","descriptio ...

Converting a json array into a map with the help of Underscore.js

My challenge involves parsing a JSON array into a map object, with the key being the state and the value being an array of objects that share the same state. An example JSON data set is provided below: { "totalRec": 10, "content": [ { "name" ...

What is the method for sending these variables via POST?

The code snippet referred to as New script is designed to produce two integer variables anchor and signed. I am interested in replacing the Old script with the New script, but there are significant differences between them. Inquiry How can I send/post t ...

display the presently active dot in the slick slider

I am currently facing an issue with my slider. It currently shows the total slide count as the number of dots, but I also want to display the current active dot number instead of the active slide number. Here is the relevant section of my code: var $status ...

Combining and grouping objects by their IDs in a JavaScript array

Information: [ { "id": "ewq123", "name": "Joshua", "order": "Pizza" }, { "id": "ewq123", "name": "Joshua", "order": ...

Issues with jQuery custom accordion functionality in Internet Explorer, Safari, and Chrome browsers

When a corresponding <a> is clicked, my script should expand/collapse UL elements. It works perfectly in Firefox and you can check it out here. First, I load the jQuery library and then my own examples.js file which includes: function initExamples( ...

Unable to consistently select a radio button via code across different browsers

Is there a way to automatically select a radio button based on the URL path? $(document).ready(function () { function checkRadioBasedOnUrl() { var urlPath = window.location.pathname.split("/"); console.log(urlPath); // ["", "tradeshow ...

Submitting a form in Rails without refreshing the page and dynamically updating the view

Hello everyone! I am currently utilizing Rails and in my process, I would like the user to perform the following steps on the same page: Input their address Completing the form Submit the form Clicking to submit Update the view to display the add ...

Issues with connecting static files in express.js

Hey there! I'm having an issue with the redirect not working when I click the "Submit" button on the login page. The code in my index.js file looks like this: app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(path.join(__dir ...

What is the best way to retrieve an accurately matched array?

I am working on a function that analyzes a string of DNA and should return an accurately matched DNA array. Here is the code snippet I have experimented with: function checkDNA(dna) { var dnaarr = []; for(var i = 0; i < dna.length; i++) { ...

Discovering the specific URL of a PHP file while transmitting an Ajax post request in a Wordpress environment

I'm currently working on a WordPress plugin and running into some issues with the ajax functionality. The main function of my plugin is to display a form, validate user input, and then save that data in a database. Here is the snippet of code for my ...

Analyzing npm directive

I have a script that handles data replacement in the database and I need to execute it using an npm command package.json "scripts": { "database": "node devData/database.js --delete & node devData/database.js --import" ...

Spotlight the content of the file obtained from GitHub

I'm having trouble with syntax highlighting for code fetched from GitHub. fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/AutomationAcc/test1.ps1") .then(response => response.text()) .then(data => document.getElem ...

Ways to conceal components upon clicking a different element

Struggling to make this jQuery function properly. I have a form with all fields contained in a div.form-group. The subscribe button is identified by the id subscribe. I'm aiming to hide the form fields when clicked, but my JavaScript doesn't see ...

Utilizing Firefox and Selenium with Python: A guide to dynamically accessing HTML elements

Currently, I am utilizing a combination of Python, Selenium, Splinter, and Firefox to develop an interactive web crawler. The Python script provides the options, then Selenium launches Firefox and executes certain commands. At this point, I am looking fo ...