Exploring JavaScript physics within a two-dimensional environment

I've been diving into learning Canvas (HTML5) on my own and I've managed to code most of a simple game engine. It's based on a 2D space theme with planets, stars, and celestial bodies. In my default "Sprite" class, there is a frame listener implemented like this:

The "baseClass" contains a function for inheriting properties and assigns "a" to "this.a". So, creating an instance like "var aTest = new Sprite({foo: 'bar'});" sets "aTest.foo = 'bar'". This is how the objects interact in my setup.

Sprite = baseClass.extend({
  init: function(a){
    baseClass.init(this, a);
    this.fields = new Array(); // List of fields of gravity one is in. Not sure if this is a good idea.
    this.addFL(function(tick){ // This will be independent of framerate soon.

      // Gobjs is an array containing all Sprite objects in the "world".
      for(i = 0; i < gobjs.length; i++){

        // Check its setup, whether it wants gravity, and ensure it's not the current sprite.
        if(typeof(gobjs[i].a) != undefined && !gobjs[i].a.ignoreGravity && gobjs[i].id != this.id){
          // Check proximity within a certain range.
          if(this.distanceTo(gobjs[i]) < this.a.size*10 && gobjs[i].fields.indexOf(this.id) == -1){
            gobjs[i].fields.push(this.id);
          }
        }
      }
      for(i = 0; i < this.fields.length; i++){
        distance = this.distanceTo(gobjs[this.fields[i]]); 

        angletosun = this.angleTo(gobjs[this.fields[i]])*(180/Math.PI); // Convert radian angle to degrees.

        // Still figuring out the gravitational effects here.
        this.a.angle = angletosun+(75+(distance*-1)/5); //todo: omg learn math

        if(this.distanceTo(gobjs[this.fields[i]]) > gobjs[this.fields[i]].a.size*10){
          this.fields.splice(i); // Out of range, stop effecting.
        }
      }
    });

    // Draw objects based on new position (from fixed velocity and angle).

  }
});

It's quite a challenge, especially that particular line which seems to make no sense at all. Degrees plus distance equals failure indeed!

this.a.angle = angletosun+(75+(distance*-1)/5);

This question leans more towards physics than Javascript, and despite reading numerous resources on orbital mathematics, it quickly goes over my head.

Answer №1

A walk down memory lane, exploring the wonders of physics simulation always brings back fond memories.

If you're looking to brush up on your vector math skills, look no further. This article covers everything you need to know about vectors, although there may be easier sources out there. Check it out here: http://en.wikipedia.org/wiki/Euclidean_vector

Your coding style seems heavily object-oriented. While preferences do vary, consider simplifying by sticking to pure data objects and separating the logic into distinct functions.

To kickstart your journey into physics mathematics, ensure each object in your simulation has a position (as a vector), velocity (as a vector), and mass.

For each iteration, remember to update the position by adding the velocity:

p = p + v

Additionally, calculate the gravitational influence between objects to adjust their velocities accordingly. For example, object B's velocity would change due to object A's gravity like this:

B.v = B.v + (A.p - B.p) * (A.m / (|A.p - B.p|^3))

Mastery of vector mathematics will enable you to translate these concepts into actual code seamlessly.

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

What could be causing the props to appear empty in a Child component within a Quasar framework and Vue 3 application?

I am facing an issue while passing props to a Child component table in my Quasar Vue3 app. The content is not being rendered, and I can't figure out why. Strangely, the console is clear of any errors. In the parent component, I am creating an object w ...

The pagination in React using React Query will only trigger a re-render when the window is in

Currently, I am utilizing React-Query with React and have encountered an issue with pagination. The component only renders when the window gains focus. This behavior is demonstrated in the video link below, https://i.sstatic.net/hIkFp.gif The video showc ...

When I try to pass a variable as a prop to another .js file, it mysteriously transforms into an undefined value

Upon successful login, my app file sets the isAuthenticated variable to true and redirects to the /admin page. The Firebase API call is functioning as expected, allowing access only with a valid username and password. The issue arises when I try to hide t ...

Footer content no longer overlapping

I'm currently utilizing Bootstrap and attempting to create a footer that stays at the bottom of the page. The issue arises when there is an excess of content, causing the footer to overlap with the content. My layout structure looks like this: <bo ...

What are the steps for fetching data using ajax?

I am looking to create a function where a user can input a country and then view its population. The JavaScript code I have is supposed to take the user's input, search for the country when a button is clicked, and retrieve the population data from a ...

Node Js Error: morgan causing TypeError - app.use is not a valid function

Just diving into the world of node js and decided to follow a tutorial on scotch.io. I added morgan for logging requests, but when I hit run, I encountered an error saying TypeError: app.use is not a function. Here's the snippet from my app.js; const ...

Use jquery to rotate the div and animate it to move upwards

Hey everyone! I'm having an issue with rotating and moving an image inside a div element. I've tried some code to make it work, but nothing seems to be happening. Any tips or suggestions on how to tackle this problem would be greatly appreciated. ...

Issue with the back-to-top button arises when smooth-scrolling feature is activated

This Back To Top Button code that I discovered online is quite effective on my website. // Defining a variable for the button element. const scrollToTopButton = document.getElementById('js-top'); // Creating a function to display our scroll-to- ...

The JSX component cannot use 'Router' as a valid element

Error Message The error message states that 'Router' cannot be used as a JSX component because its return type 'void' is not a valid JSX element. TS2786 import App from './App'; 5 | > 6 | ReactDOM.render(<Router ...

directive behaves unexpectedly in bootstrap grid

I'm a new AngularJS user:). Having an issue with my directive that controls popovers for icons. It's functioning properly in one location but malfunctioning in another (blinking and causing the popup to shift down and cover the icon). HTML temp ...

Close to completing the AngularJS filter using an array of strings

I'm currently working on developing a customized angular filter that will be based on an array of strings. For instance: $scope.idArray = ['1195986','1195987','1195988'] The data that I aim to filter is structured as fo ...

Saving solely the content of an HTML list element in a JavaScript array, excluding the image source

One issue I am facing is with an unordered list in HTML which contains items like <ul id="sortable"> <li class="ui-state-default"><img src="images/john.jpg">John</li> <li class="ui-state-default"><img src="images/lisa.jpg ...

Developing with Angular 1.4.8 and JavaScript involves the process of building a constructor function to inherit properties into a third object

DEVELOPER TOOLS Using Angular 1.4.8 and lodash QUERY: REVISIT To clarify my query: Create an object (articles) Apply a constructor Import the properties of a third object, but place it in proto folder to prevent cluttering the root with a large colle ...

Run the function once the page has completed downloading and bootstrapping

After experimenting with $evalAsync and $viewContentLoaded, I've found that they only trigger after Angular has completed populating the template. My goal is to determine, from within a directive: Is the template fully replaced by Angular? Have all ...

Axios successfully fulfills a promise despite the request being canceled while using React.StrictMode

In my React project, I'm using axios with React.StrictMode enabled by default, causing components to render twice. To handle this behavior, I've set up an abort control for my axios instance and call its abort() method in the useEffect clean-up f ...

Is there a way to use JavaScript to import several custom fonts at once?

Is there a way to import a long list of custom fonts as icons using Javascript? I have been obtaining the font list from an API, but importing them one by one with pure CSS using @font-face is time-consuming and difficult to maintain. @font-face { fon ...

Tips for extracting geographic location information from image file metadata using JavaScript

Is there a way to extract geolocation data from an image file (JPG, JPEG, PNG, etc) using Javascript when the file is being loaded onto a web browser, before it is actually uploaded by the client? ...

Struggling to modify a nested object in the state

import React, { Component } from 'react'; import ColorBox from './ColorBox' import './ColorBoxes.css' class ColorBoxes extends Component { state = { colors: {} } clickedColor = (color) => { le ...

My method for updating form input properties involves switching the disable attribute from "false" to "true" and vice versa

I have a form that uses Ajax to submit data. Once the user submits the form, the text is updated to indicate that the data was sent successfully, and then the form is displayed with the fields filled out. I want to display the form but prevent users from r ...

Stopping the animation of scrollLeft upon user interaction can be achieved by utilizing JavaScript

Here is my current code snippet: <script> $(document).ready(function() { $('.scrolls').stop().animate({ scrollLeft : 4000 },100000, 'linear') }) </script> I am looking for a way to halt the animation once ...