formula for an arbitrary velocity vector

In the game I'm developing, I want the ball to move in a random direction on the HTML canvas when it starts, but always with the same velocity. The current code I have is:

vx = Math.floor(Math.random() * 20)
vy = Math.floor(Math.random() * 20)

However, this does not provide a consistent velocity. Can anyone suggest a formula that will achieve this? Thank you.

Answer №1

Are you looking to achieve a consistent velocity with a sporadic trajectory? If so, consider using the following formula:

phi = 2*Math.PI*Math.random();
vx = speed * Math.cos(phi);
vy = speed * Math.sin(phi);

Answer №2

It seems like you are working in Java and looking to generate a random vector with a magnitude of 20?

Initially, the vector produced by Math.random() is not truly random as it generates a number between 0 and 1, causing the vector to always point towards the same quadrant in the coordinate system (both coordinates positive). To achieve true randomness, consider using Math.random()*2 - 1 to create coordinates ranging from -1 to 1.

Additionally, it is important to normalize your vector for accurate results. You can refer to this link for more information:

Finally, adjust both vector coordinates by multiplying them by the desired magnitude, such as 20 in your case.

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

styling multiple elements using javascript

Recently, I created a jQuery library for managing spacing (margin and padding). Now, I am looking to convert this library to pure JavaScript with your assistance :) Below is the JavaScript code snippet: // Useful Variables let dataAttr = "[data-m], [d ...

The scroll function is failing to activate at the desired location

I've been trying to fine-tune a window scroll function I created. Initially, I attempted to use waypoints for this, but unfortunately, I couldn't get it to work as expected. The main issue I'm facing is that the function triggers too early ...

The issue of "Next.js localStorage not being defined persists, despite attempting to

Despite encountering numerous similar questions, I have not been able to find a solution to my specific issue. This is my first experience utilizing Next.js and TypeScript. I am conducting a mock login with REQRES and storing the token in the localStorage ...

Issue with responsive design: Media queries not applying max-width

GOAL I want the content of my page to adjust to screen sizes that are smaller than 600px wide. ISSUE When using the responsive tool in Chrome, preset screen sizes like iPhone X do not apply media queries properly. Even manually adjusting the screen size ...

When the last character in the route is a forward slash, the Express server will load the HTML page with CSS and JavaScript. Conversely, if the last route character

On my second html page model.html, I noticed the following issue: When I include a '/' at the end of my route address in the browser like this: http://localhost:3002/home/model/, the correct html page is loaded, but the css/js files do not load. ...

Mapping API for JavaScript, converting coordinates into precise locations

I have two coordinates: 54.674705589 and 25.289369548. I want to place these coordinates on a map when the button is clicked, similar to this example. However, the example provided is for addresses, not coordinates. Is it possible to modify this example t ...

PrimeNG - Sticky header feature malfunctioning in the p-table

Hello there, I am currently using PrimeNG p-table which features both horizontal and vertical scrolling. My goal is to implement a sticky header for the table, so far I have attempted two methods: [scrollable]="true" scrollHeight="350px" ...

Having trouble with Laravel routes and jQuery $.post()? Keep getting a frustrating 404 Not Found error?

A JavaScript file with jQuery that is responsible for sending a POST request $.post('log_in', { email: email, password: password }, function(response) { $('#log_in_result').html(response); console.log(response); }); In the Lar ...

Can you help me identify the issue with this code? It works fine when I don't include the dimensions, but as soon as I add them, the entire page disappears

After removing the dimensions, everything appears fine. But as soon as I add them back in, the entire page disappears. I'm struggling to understand why that is happening? $src = $row['product_image']; echo "<td>"."<img src="$src" h ...

Issue with konvaJS when trying to simultaneously resize, drag, and apply filters to an image

Looking for help with resizing, dragging, and filtering images using Konvajs 2d canvas library? If the images are not resizing properly after applying a filter, can someone assist me? Note: Please be aware that when using Google image URLs, there may be c ...

Retrieving a specific attribute pair from a JSON object

Currently, I am trying to retrieve the temperature data and display it on my webpage. Since these are objects with no specific order, I am struggling to understand how to access them without using an index. { "response": { "version": "0.1", "termsofServic ...

Unable to eliminate blue highlighting in Chrome when an element is in focus

After clicking on the search button, there seems to be a persistent blue outline that CSS is not correctly removing despite the settings I've applied. Here is the CSS code I have used: input:focus { -webkit-tap-highlight-color: rgba(0,0,0,0); outl ...

Using jQuery's ajax function to send data with a variable name of data field

I am trying to figure out how to dynamically add a variable to the name of the data field I want to send information to through ajax. Below is an example of the code I'm working on: var qty = $('#qty_'+value).val(); $.ajax({ url: &apo ...

How to Adjust Overlapping Text in CSS?

Currently, I am facing an issue with an element overlapping in my CSS file. On a regular browser, one line of text appears fine but on mobile devices, it overlaps into two lines. This problem is specifically for the mobile version of the website, particula ...

"Enable a smooth transition and switch the visibility of a div element when clicked

How to create a dropdown form with a transition effect that triggers on click of an element? Once triggered, the transition works smoothly but clicking again only hides the div element without triggering the transition. See the demo here: Check out the fu ...

"Learn the steps to dynamically update the ng-bind value of a single element within an ng-repeat loop by

I'm new to Angular and I'm working on developing a shopping cart. I'm currently facing an issue with adding the 'Added!' value when clicking on the "add to cart" button. Here is my code <div ng-repeat="item in products"> < ...

Guide on parsing JSON data received from the frontend

Here is the HTML code that I am working with: <div id="loginform"> <form class="loginIn" name="loginform"> <input type="text" name="login"> <input type="password" name="password"> <input type="submit" value="Войт ...

Concealing the rear navigation button within the material carousel

I have a material css carousel, and I am trying to hide the back button on the first slide. I attempted to use the code below from a previous post The following code snippet prevents the user from looping through the carousel indefinitely. Stop looping i ...

The text is not displaying as expected due to a timeout issue

Trying to create a pop-up that functions as follows: After 3 seconds, the close button should appear, but during those 3 seconds, there will be a countdown. However, I'm encountering an issue where no text is being displayed. var n = 3; function p ...

The functionality of the onclick and onserverclick attributes seem to be malfunctioning when

I am in the process of creating a basic login screen using the code provided below: <form id="login"> <div class="formHeader"> <h1>Login</h1> </div> <div class="formDiv"> <input type="text" placeholder="Email" na ...