Calculating the required force vector to score a basketball shot using Ammo.js and Three.js

Currently in the process of developing a basketball game using three.js and ammo.js. The positions of the hoop/rim and ball are constantly changing, making the shots dynamic and relative.

I am tasked with determining the correct force vector needed for a successful shot. As part of the gameplay, users will swipe to shoot, influencing the ideal force required for the "perfect shot."

I have come across various examples of code and equations for trajectory calculations, ballistics, etc., which I have been converting from C# to JavaScript as most of the resources I find are on Unity forums.

For this project, I require a function that can calculate the initial force vector3 to be applied to the ball based on factors such as the ball's position, the hoop's position, the mass of the ball, and gravity. Additionally, the function will need to receive the initial angle or maximum height (terminal velocity y) as parameters, as observed in existing equations and calculators.

UPDATE:

In my exploration, I adapted a script sourced from Unity forums into JavaScript/Three.js format:

insert converted JavaScript code here

The function is being called in this manner:

const velocity = getBallVelocity( ball.position, rim.position, 45 );
ball.body.applyForce( velocity.x, velocity.y, velocity.z )

However, the shot is incorrect in direction and lacks power. It appears there may be an issue with the rotation at the end of the function, while the weak shot could be due to a lack of appropriate mass multiplication. The ball has a mass of 2, so it might be necessary to multiply certain Y values by 2? Any guidance would be appreciated!

Below is the original C# script that served as the basis for my conversion attempt:

insert original C# script here

Thank you!

Answer №1

Alright, I've made some key adjustments:

  1. Replaced the flawed velocity rotation method with atan2.
  2. Corrected the Y axis subtraction for determining yOffset.
  3. Switched from using applyForce to setVelocity function.

Check out the updated script below, hopefully it proves useful!

static getBallVelocity( ballPos, rimPos, angleDegrees, gravity ){
 
  // Convert angleDegrees to radians
  const angle = THREE.Math.degToRad( angleDegrees );
 
  gravity = gravity || 9.81;
 
  // Define positions on the same plane
  const planarRimPos  = new THREE.Vector3( rimPos.x, 0, rimPos.z ),
        planarBallPos = new THREE.Vector3( ballPos.x, 0, ballPos.z );
 
  // Calculate planar distance between objects
  const distance = planarRimPos.distanceTo( planarBallPos );
 
  // Determine offset along the y axis
  const yOffset = ballPos.y - rimPos.y;
 
  // Calculate initial velocity
  const initialVelocity = ( 1 / Math.cos( angle ) ) * Math.sqrt( ( 0.5 * gravity * Math.pow( distance, 2 ) ) / ( distance * Math.tan( angle ) + yOffset ) ),
        velocity = new THREE.Vector3( 0, initialVelocity * Math.sin( angle ), initialVelocity * Math.cos( angle ) );
   
  // Rotate velocity to align with object direction
  const dy = planarRimPos.x - planarBallPos.x,
        dx = planarRimPos.z - planarBallPos.z,
        theta = Math.atan2( dy, dx ),
        finalVelocity = velocity.applyAxisAngle( PopAShotAR.Vector3.up, theta )
 
  return finalVelocity;
}

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

Is it possible to make a Javascript AJAX request without using server-side code?

I am currently working on a JavaScript file where I am attempting to make an AJAX call in order to retrieve JSON data. $.ajax({ type: "POST", url: "er.js", // this is the same file data: { action: 'analyzePost&ap ...

JavaScript can be used to arrange a table in both ascending and descending order by simply clicking on the header

window.addEventListener('DOMContentLoaded', () => { let dir = "dsc"; th = document.getElementsByTagName('th'); for(let c=0; c < th.length; c++){ th[c].addEventListener('click',item(c)); } ...

What is the reasoning behind CoffeeScript automatically adding a function when extending an Object?

I'm currently working on a helper method to identify the intersection of two hashes/Objects in this manner... Object::intersect = (obj)-> t = {} t[k] = @[k] for k of obj t x = { a: 1, b: 2, c: 3 } w = { a: true, b: 3 } x.intersect(w) #=> ...

Display or conceal several elements upon hover using JQuery and HTML

Here is the current progress I have made: <div style = "position: relative;"> <a href = "#games"> <div class="sidenavOff"> <img src = "images/card_normal.png" /> <img src = "images/category_icons/icon_games.png" style = "positio ...

Tips on preventing the insertion of special characters into a form field with the help of jQuery

I'm implementing a feature to restrict users from using special characters in the text input field. While I have successfully prevented users from typing these characters, I am also looking to prevent the pasting of any special characters as well. FID ...

Retrieve data using $http.get when an accordion group is expanded in AngularJS

Currently, I am utilizing Angular v1.2.0rc1 along with Angular-UI Bootstrap. [edit] My objective is to implement a load-on-demand feature with caching while incorporating an accordion functionality. The accordion group that I am using can be found here. ...

The operation malfunctions if the variable input is below 50, causing it to produce inaccurate results

The function "calcFinalTotal()" was created to calculate the post-tax discount on a purchase of items that were previously totaled and stored in an input tag with the ID of "totaltaxamount". This function applies a 10% discount to orders between $50 to $ ...

I need to display the product name associated with the product_id found in the line_items array within the order table. I aim to achieve this functionality by utilizing Laravel with Vue.js

In my database, there is a cell called line_items in the orders table that contains data like: [ {"customer_id":"30","product_id":"10","unit_id":"2","quantity":"1","price":"2700","total_price":"2700"}, {"customer_id":"30","product_id":"43"," ...

having trouble transferring data from one angular component to another

I've been attempting to send data from one component to another using the service file method. I've created two components - a login component and a home component. The goal is to pass data from the login component to the home component. In the l ...

Performing a cross-domain JSON Get request with JQuery

Struggling with a simple JSON get request to an API on a domain that I don't have control over. Here's the code I'm using: $(document).ready(function () { $.ajax({ type: 'GET', url: 'http://pu ...

Find the months where two date ranges overlap with the help of date-fns

Is there a way to find the overlapping months between two date intervals using date-fns? const range1 = { start: new Date('2018-01-01'), end: new Date('2019-01-01') } const range2 = { start: new Date('2018-07-03'), end: new D ...

Establish a timeout period when using the hover function

My dynamically loaded content requires a specific method of invocation due to its unique nature. While the process runs smoothly without using a setTimeout, is there any way to introduce a 0.25 second delay in this scenario? Check out this fiddle for ref ...

What is the most effective way to ensure that a child component only executes when a link is clicked on the Vue component?

There are two components in my code The first component, which is the parent component, looks like this : <template> <ul class="list-group"> <li v-for="item in invoices" class="list-group-item"> <div class="ro ...

Jquery Validate doesn't consistently give a positive response

Having a button that triggers the jQuery validation plugin poses an issue where it consistently returns true, except when the fields are left empty. The rules set for validation seem to be disregarded. DEMO http://jsfiddle.net/sw87W/835/ $(document).read ...

Display the modal in Angular 8 only after receiving the response from submitting the form

I am encountering an issue where a pop-up is being displayed immediately upon clicking the submit button in Angular 8, before receiving a response. I would like the modal to only appear after obtaining the response. Can someone assist me with achieving thi ...

Challenges with Vuex and updating arrays using axios

I am currently facing a challenge with VueJS Vuex and Axios: The issue arises when I retrieve an array with Axios and loop through it to populate its children this way: "Rubriques" has many self-relations, so one rubrique can have multiple child rubriques ...

Can components be designed in a way that includes elements such as buttons or text areas in the code, but allows for them to be excluded when the component is used?

I have a custom form component that I designed. Depending on certain cases, I want the form to display either a button or a text field instead of the input field as currently coded. function FormTypeOne(props) { return ( <form className={classes.f ...

Is it possible to include a subscription to a PayPal purchase post initial checkout?

Our company specializes in providing digital online training courses. Through our experience, we have discovered that our conversion rates are significantly higher when users go through the standard checkout process first and then are given the option to s ...

Unspecified origins of Js in Chrome Extension

console.log(chrome.runtime.sendMessage({from:"script2",message:"hello!"})); However, attempting to send the message from a background script to a content script is proving to be unsuccessful. https://i.stack.imgur.com/ERgJB.png ...

Is there a way to integrate Javascript code with a React component?

I need to find a way to include this block of code in just one specific React component. Any suggestions? <!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. --> <button sty ...