so i am making a thing in javascript and i want to have planetary gravity in my "universe".

But when i use an equation to calculate the acceleration by gravity i get one number. That is how fast the object accelerates in the direction of the other object, but how do i convert a speed in one direction to a speed in the X, Y and Z axis?

  • \$\begingroup\$ Do you used Newton formula F=G*(M+m) / R^2 ? How do you calculated R ? \$\endgroup\$ Jan 2 '16 at 11:02
  • \$\begingroup\$ I used Newton's law of universal gravity (F=GmM/r^2) and converted the newtons you get from the equation to distance. See how i calculated the distance here: mathsisfun.com/algebra/distance-2-points.html \$\endgroup\$
    – DayDun
    Jan 2 '16 at 11:08
  • 1
    \$\begingroup\$ you need some vector math : mathsisfun.com/algebra/vectors.html . The direction from A to B is B-A (vector difference) normalized. So (B-A)/r where r is distance. \$\endgroup\$ Jan 2 '16 at 11:31

Gravity is additive. Calculate the gravity generated by planet A at point x. Then multiply by a unit vector pointing from x to A - that returns a vector, which gives the gravity a direction. Repeat for planet B, C, etc, then add the vectors.

Velocity is acceleration times time. Every frame, multiply the acceleration vector by the delta time, and add the result to the velocity vector. You can access x, y and z of the velocity vector directly.

A vector simply stores the x, y, and z components independently. A unit vector is a vector of length one - you make a unit vector by taking your vector and dividing each component by it's length, the length is length = sqrt(x*x+y*y+z*z). You add vectors by adding the components independently. You multiply a vector by a constant like gravity by multiplying it's components independently.

  • \$\begingroup\$ I know gravity is acceleration. But how do i convert the vector to x, y and z velocity? \$\endgroup\$
    – DayDun
    Jan 2 '16 at 11:10
  • \$\begingroup\$ well, i don't really know what a vector is, but i asume that it is a thing that stores the acceleration of x, y and z or something. I am coding in javascript so should i create an array with three numbers or what? The thing is, i have the speed and the direction, how do i convert it to x, y and z speed? \$\endgroup\$
    – DayDun
    Jan 2 '16 at 11:20
  • \$\begingroup\$ @DayDun Updated the answer \$\endgroup\$
    – Peter
    Jan 2 '16 at 11:31
  • \$\begingroup\$ You're trying to do physics without having a minimal background in the math involved. Your time is better spent reviewing en.wikipedia.org/wiki/Classical_mechanics before trying to implement a custom solution. \$\endgroup\$ Jan 2 '16 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.