Discovering the optimal angle and ballistics formula for calculating a projectile's trajectory in Three.js

Utilizing FlyControls.js for my camera perspective

I am attempting to incorporate a projectile into my object

The projectile is meant to utilize the angles between the camera position and the crosshair/reticle position, moving freely through 3D space

My attempt using

camera.position.angleTo(crosshair.position)
only yields a single float value. In 2D scenarios, I would employ sin and cos, but 3D requires a different approach

Additionally, since the projectile is in the form of a cylinder, how do I orient it to face the direction of travel?

//how can this be achieved?
projectile.angle = {
    x: ?,
    y: ?,
    z: ?,
};

//how can this be accomplished?
projectile.rotation = faceTowardsDestination;

function animate(){
    //implementing projectile motion
    projectile.position.x += projectile.angle.x * projectile.speed;
    projectile.position.y += projectile.angle.y * projectile.speed;
    projectile.position.z += projectile.angle.z * projectile.speed;

    requestAnimationFrame(animate);
}

The projectile (cylinder) should be launched from the spaceship towards the crosshair point, while facing its intended destination https://i.sstatic.net/rfPCy.png

Answer №1

If you're looking to align an object with a specific point, check out the Object3D.lookAt(vec3) method here for more details. This function will orient the object towards the designated position.

// Define the coordinates of the target
const target = new THREE.Vector3(x, y, z);

// Adjust the object to face the target location
projectile.lookAt(target);

let speed = 1;

function animate() {
    // Move the object forward by translating along its own Z-axis
    projectile.translateZ(speed);
    requestAnimationFrame(animate);
}

If your projectile is already facing the desired direction, simply move it along its local Z-axis (not the global z-axis) without concerning yourself with the X & Y coordinates.

Answer №2

To ensure a projectile moves towards the crosshair, you must first project the crosshair's location far ahead of the camera.

One effective method is to create an infinite plane as a child of the camera, position it at a distance, and then employ a Raycaster to determine where the crosshair intersects with this plane. Check out how intersection works between the mouse pointer and a surface here.

The directional vector from your ship's position to this intersection point indicates the travel direction for your projectile. Adjusting the ship's rotation accordingly may be necessary.

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

Having difficulty executing the playwright tests

Trying to execute the playwright test from the specified location results in a message prompting to run npm install -D @playwright/test before running the test. Despite having already installed playwright as a dev dependency, the test is still not being ex ...

Executing `console.log()` in Windows 8 using JavaScript/Visual Studio 2012

Whenever I utilize console.log("Outputting some text") in JavaScript within Visual Studio 2012 for Windows 8 metro development, where exactly is the text being directed to? Which location should I look at to see it displayed? Despite having the "Output" pa ...

Instructions on directing api endpoint to user's localhost once deployed on Heroku

I have encountered an issue with my API. It works flawlessly when tested locally, but once deployed to Heroku, I receive a 503 error. This occurs because the API is attempting to target localhost on Heroku's server instead of the user's localhost ...

What is the best way to define defaultProps for a nested object?

Within a react component, there is a nested object defined in the propTypes. This setup is functioning correctly. UserCard.propTypes = { name: PropTypes.string, customer: PropTypes.shape({ email: PropTypes.string, phoneNumber: PropTypes.string, ...

How can you deselect nested checkboxes while maintaining the currently selected checkbox using jQuery?

In my WordPress site, I have a structure of nested checkboxes within ul and li elements. Here is the HTML code: <ul class="woof_list woof_list_checkbox"> <li> <label class="woof_checkbox_label" for="woof_uncheck">Parent Categor ...

A JavaScript function that fetches the color name based on either the RGB value or the Hexadecimal value

Looking for a JavaScript function that can determine the name of a color. Would like the JavaScript function to be structured as shown below: function getColorName(r, g, b) { .... return <color name>; // such as blue, cyan, magenta, etc. } ...

Tips for implementing a dynamic value in the ng-style based on certain conditions

Is there a way to set a background-color conditionally using ng-style when the color value can be updated from $scope? These are the variables in my scope: $scope.someone = { id: '1', name: 'John', color: '#42a1cd' }; $scope ...

I am looking to create a cascading dropdown list in C# MVC that pulls data from various SQL tables. How can I achieve

I am currently working on a C# MVC web application and facing a challenge in implementing a cascading drop-down list. While I have come across various articles discussing this topic, the uniqueness of my requirements makes it difficult for me to figure out ...

Troubleshooting the issue of AJAX not successfully transmitting variables to PHP

let xmlhttpRequest; if (window.XMLHttpRequest) { xmlhttpRequest = new XMLHttpRequest(); } else { xmlhttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttpRequest.open("POST", "test.php", true); xmlhttpRequest.setRequestHeader("Content-typ ...

Efficient jQuery Algorithm for Calculating Image Viewport Sizes Without Scrollbars

I am trying to create an image hover effect, but I am encountering an issue. When I hover over certain images, unwanted scrollbars appear, and I would like to find a way to prevent this from happening. It seems to be related to the viewport and calculation ...

Can somebody please tell me the equivalent of the sleep() function in JavaScript?

Are there more efficient ways to implement a sleep function in JavaScript compared to the pausecomp function as shown below (sourced from here)? function pausecomp(millis) { var date = new Date(); var curDate = null; do { curDate = new Date(); ...

Determine if the browser displays <select multiple> as a modal dialog

Is it possible to use JavaScript to detect whether a specific browser displays a focused <select multiple> element as a popup or strictly as an inline box? On certain platforms, like the Android Browser and iOS Safari, the appearance of a popup can ...

Retrieve the player's name from the database using jQuery

How can I retrieve the text value from my scores table in the database? Here is an image of my score table: https://i.stack.imgur.com/CUiMw.png The Player_name is stored as Player_id, which is a foreign key from the players' table. While I c ...

What is the process for consumers to provide constructor parameters in Angular 2?

Is it possible to modify the field of a component instance? Let's consider an example in test.component.ts: @Component({ selector: 'test', }) export class TestComponent { @Input() temp; temp2; constructor(arg) { ...

Utilize pg-promise for inserting data with customized formatting using the placeholders :name and :

After reviewing the pg-promise documentation, I came across this code snippet: const obj = { one: 1, two: 2 }; db.query('INSERT INTO table(${this:name}) VALUES(${this:csv})', obj); //=> INSERT INTO table("one"," ...

The paragraph was unable to start in a new line as expected

After spending the past couple of hours scouring the internet and trying various solutions, I have come up empty-handed. My dilemma revolves around attempting to create a line break within a paragraph, but no matter what I try, it doesn't seem to work ...

Await that's locked within a solo asynchronous function

async function submitForm(e){ e.preventDefault() console.log(e.target) try { const response = await axios.post('/api/<PATH>', {username, password}); console.log(response.data); const token = response.data.token if (t ...

What is the reason behind the significant 80% reduction in PNG files by grunt-contrib-imagemin compared to the minimal reduction of less than 0.1%

Just getting started with Grunt here. Recently, I've been experimenting with grunt-contrib-imagemin. When it comes to compressing PNG files, it does an impressive job. It typically reduces the size by around 80%. However, I'm finding that the ...

Error in Express.js Routing: Headers cannot be set after they have already been sent

I am facing an issue that I can't quite understand: "Error: Can't set headers after they are sent." This is a basic API created with express.js to verify if a user is logged in or not. If the user is not logged in, they should be red ...

Using JavaScript to shift an image sideways upon clicking a hyperlink on the page

One of my clients has a unique request for an image to move across the page from left to right when a link is clicked. I'm not very experienced with javascript, so I would really appreciate any guidance on how to make this happen. Thank you in advanc ...