简体   繁体   中英

How to apply 2D gravitational effects to sprites

Within a 2D infinite space, I have two circular sprites that represent massive bodies in outer space.

Each body has a pair of x , y coordinates, a mass , a speed and a direction (in radians).

On each frame of animation, I'm running the following code for each body (where this is the body being updated, and other is the other body):

x, y = other.x - this.x, other.y - this.y

angle = atan2(y, x)
distance = root(square(x) + square(y))
force = this.mass * other.mass / square(distance)

Note: I'm ignoring G as it's just a multiplier.

I know how to move the bodies around, based on their coordinates, speed and direction, but do not know how to update this.speed and this.direction to simulate gravity.

The gravitational force acting on a given body is represented as a vector and produces acceleration with components ( ax and ay ), which are calculated (based on what you already have) like this:

squared_distance = square(x) + square(y)
distance = sqrt(squared_distance)

accel = other.mass / squared_distance    
ax = accel * x / distance 
ay = accel * y / distance

Note that the angle (force/acceleration direction) is not needed.

Each body should have an associated velocity (instead of speed ), which should be a two-component vector ( vx and vy ). It is updated like this (where dt is the time interval between updates):

this.vx += ax * dt
this.vy += ay * dt

Once the velocity of a given body has been updated, it can then be repositioned (updating its x , y coordinates) like this:

this.x += this.vx * dt
this.y += this.vy * dt

You can calculate the speed and direction if you need them, but they are not needed here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM