Determining the angular difference between the direction of particle motion and a straight line

Currently, I am in the process of developing a simulation involving a bouncing ball. In this simulation, users have the ability to place lines on the canvas that the ball can collide with by dragging from one point to another. There are specifically four types of lines that can be generated:

https://i.sstatic.net/qxINA.png

The structure that represents a line is outlined as follows:

export interface pathSection {
    xfrom: number;
    yfrom: number;
    xto: number;
    yto: number;
    length: number;
}

It is important to note that the first and third lines in the image do not produce identical values from

Math.atan2(yto - yfrom, xto - from);

Given the intricate nature of the surfaces involved, it is necessary to determine the angle between a moving object and the surface at the moment of collision:

https://i.sstatic.net/tVQZY.png

When the ball collides with the surface, it does so at an angle denoted as 'a'.

However, I am encountering difficulties in calculating the angle between the two vectors. Here is my current approach:

var dx = this.path[index_for_path_section].xfrom - this.path[index_for_path_section].xto;
var dy = this.path[index_for_path_section].yfrom - this.path[index_for_path_section].yto;
var posX = this.particle.pos.x;
var posY = this.particle.pos.y;
var posNextX = posX + this.particle.v.x;
var posNextY = posY + this.particle.v.y;

var angleOfRamp = Math.atan2(dy, dx);
var angleOfvelocity = Math.atan2(posNextY - posY, posNextX - posX);
var angleBetween =  angleOfRamp - angleOfvelocity;

This calculation is then utilized to determine the object's speed post-collision:

var spd = Math.sqrt(this.particle.v.x * this.particle.v.x + this.particle.v.y * this.particle.v.y);
var restitution = this.elasticity / 100;

this.particle.v.x = restitution * spd * Math.cos(angleBetween);
this.particle.v.y = restitution * spd * Math.sin(angleBetween);

However, the angle calculated seems to be approximately -4.5 Pi, translating to around -90 degrees when the object is moving directly downward and the surface is inclined at approximately 45-60 degrees...

https://i.sstatic.net/BQ4bh.png

The red arrow indicates the trajectory of the object intersecting with the surface - the white dots signify points where a collision has been detected between the object and the surface.

If you have any insights on how to accurately determine the applicable angle between the two velocities and the line, your assistance would be greatly appreciated!

Please note that I have made an attempt to reference this solution, but I have encountered difficulties in adapting it to fit my specific project.

Answer №1

After spending some time on it, I have managed to make it work although I still don't fully understand why because I find the JavaScript angles system a bit challenging. Here is the code snippet that helped me achieve the desired outcome:

var dx = this.path[collided].xfrom - this.path[collided].xto;
var dy = this.path[collided].yfrom - this.path[collided].yto;
var spd = Math.sqrt(this.particle.v.x * this.particle.v.x + this.particle.v.y * this.particle.v.y);
                 
var angleOfRamp = Math.atan2(dy, dx);
var angleOfvelocity = Math.atan2(this.particle.v.y, this.particle.v.x);
var angleBetween =  angleOfRamp * 2 - angleOfvelocity; // I'm still unsure why this works :)

if (angleBetween < 0) { angleBetween += 2*Math.PI; } // I'm not quite sure about this part :)

const restitution = this.elasticity / 100;

this.particle.v.x = restitution * spd * Math.cos(angleBetween);
this.particle.v.y = restitution * spd * Math.sin(angleBetween);

I appreciate all the help from everyone who checked this out :)

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

To ensure proper formatting, I must include a comma operator for numbers while typing and limit the decimal places to two

Could someone assist me in formatting a number to include commas and restrict the decimal places to two using regex? I have attempted the following, but need help making it work properly. Currently, when I enter a number it shows up as 1231244, however I ...

`Implementing Typescript code with Relay (Importing with System.js)`

Is there a way to resolve the error by including system.js or are there alternative solutions available? I recently downloaded the relay-starter-kit (https://github.com/relayjs/relay-starter-kit) and made changes to database.js, converting it into databas ...

Private route displaying unexpected behavior when making API call

A snippet of code I have been working on is partially functioning (refer to the last paragraph for a detailed description): App.Js: export default function App() { const [isLoggedIn, setisLoggedIn] = useState(null); const logIn = () => { setisLogg ...

Utilize Twilio to forward messages to a different phone number

I am seeking a solution to automatically forward incoming messages from one Twilio number to another, based on the original sender's number. For example: If I receive a message on my Twilio number "+14444444444" from '+15555555555', I want ...

Switching the cursor to the following input after a paste event using JQuery

I am currently working on an HTML form that consists of multiple input boxes. I'm looking to focus on the next input box after pasting content into one of them. Below is the code snippet I have been using: $("input").bind('paste', function( ...

Is it possible to utilize ajax for submitting a form only after it has been validated by the

Currently, I am utilizing a jQuery plugin for validation and incorporating AJAX for form submission. My objective is to submit the form only after successful validation; however, the issue arises where the form gets submitted regardless of the validation o ...

Get information that has been uploaded using ajax

I need help with my code for sending data via ajax to an update.php page. $(document).ready(function() { $("#modify").click(function() { var a = $("#a").val(); var b = $("#b").val(); var c = $("#c").val(); $.ajax({ type: "POST", ...

What is the best way to incorporate additional features into the HTML content that I display using Express?

Currently, I am working on a project using NodeJS and express in order to capture data from a form and save it to a local file on my computer. Since I am developing locally (localhost), the local file is located on my server. While I have successfully rend ...

Tips for eliminating flicker upon the initial loading of a webpage caused by dynamic changes in CSS styles through JavaScript

Struggling with the load order of my CSS and JavaScript... Currently, I have a div with a blue background that is styled to appear sliced diagonally. However, upon initial page load (or CTRL+SHIFT+R), there's a brief moment where the slice effect doe ...

Using Vue to alter data through mutations

Greetings! I am currently in the process of developing a website for storing recipes, but as this is my first project, I am facing a challenge with modifying user input data. My goal is to create a system where each new recipe added by a user generates a u ...

Employees are unable to operate within an HTML page embedded in a WPF project

When running scripts on an HTML page, the page tends to freeze until the script completes. This is why I am considering using workers. However, I have encountered a problem: <html> <head> </head> <body> <button onclick="startWor ...

Executing Promises in a loop: TypeScript & Angular with IndexedDB

Currently, I am working on a data synchronization service where data is being retrieved from a web service and then stored in IndexedDB. In my TypeScript Angular Service, the code looks something like this: this.http .post(postUrl, postData) .suc ...

Divide the string into separate JSON and non-JSON components

Here is a string I have: const str = '{ "foo": { "bar": { "baz": 5 } } } Some additional text'; Is there a reliable method in JavaScript to separate the JSON part from the non-JSON part of this string? The string always starts with valid JSON, ...

"Enhance Your Text Fields with Angular2 Text Masks for Added Text Formatting

Is there a way to combine text and numbers in my mask? This is what I am currently using: [/\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] The above code only allows for numbers. How can I modify it to allow f ...

Is there a specific minimum height that should be set for the equalHeight function to apply?

Despite trying everything, I can't seem to achieve the dreadful layout my designer has given me without using JavaScript! The issue lies with the positioning of the div #backgr-box, which needs to be absolutely positioned behind the #contenuto ( ...

Tips for dynamically coloring table cells in Spotfire based on their values

Creating Dynamic Table with HTML After successfully creating a cross table in Spotfire, I now aim to replicate the same table in HTML within a text area. I managed to add values using calculated values, but I'm stuck on how to dynamically set the bac ...

The dropdown list is not getting populated with data retrieved from an HTTP response

My experience with making HTTP calls is limited, and I am facing an issue while trying to populate specific properties of each object into a dropdown. Despite attempting various methods, such as using a for loop, the dropdown remains empty. created(){ a ...

When the mouse hovers over the slider, the final image jumps into view

After successfully building an image slider that displays 2 partial images and 1 full image on hover, I encountered a bug when setting the last image to its full width by default. This caused a temporary gap in the slider as the other images were hovered o ...

Tips for extracting data from a JQuery table with Python

My goal is to extract information from the top ten items on a manga website using Python Selenium/BeautifulSoup. However, I am facing challenges due to the website loading its content through a jquery script. The tutorials and guides I have followed do not ...

Error: Trying to access 'whenReady' property of undefined variable is not allowed

As a beginner in electron app development, I am facing an issue when running npm start from the terminal. The error message I receive is: TypeError: Cannot read properties of undefined (reading 'whenReady')... This specific problem seems to be ...