views:

516

answers:

6

I'm implementing a 2D game with ships in space.

In order to do it, I'm using LÖVE, which wraps Box2D with Lua. But I believe that my question can be answered by anyone with a greater understanding of physics than myself - so pseudo code is accepted as a response.

My problem is that I don't know how to move my spaceships properly on a 2D physics-enabled world. More concretely:

A ship of mass m is located at an initial position {x, y}. It has an initial velocity vector of {vx, vy} (can be {0,0}).

The objective is a point in {xo,yo}. The ship has to reach the objective having a velocity of {vxo, vyo} (or near it), following the shortest trajectory.

There's a function called update(dt) that is called frequently (i.e. 30 times per second). On this function, the ship can modify its position and trajectory, by applying "impulses" to itself. The magnitude of the impulses is binary: you can either apply it in a given direction, or not to apply it at all). In code, it looks like this:

function Ship:update(dt)
  m = self:getMass()
  x,y = self:getPosition()
  vx,vy = self:getLinearVelocity()
  xo,yo = self:getTargetPosition()
  vxo,vyo = self:getTargetVelocity()
  thrust = self:getThrust()

  if(???)
    angle = ???
    self:applyImpulse(math.sin(angle)*thrust, math.cos(angle)*thrust))
  end
end

The first ??? is there to indicate that in some occasions (I guess) it would be better to "not to impulse" and leave the ship "drift". The second ??? part consists on how to calculate the impulse angle on a given dt.

We are in space, so we can ignore things like air friction.

Although it would be very nice, I'm not looking for someone to code this for me; I put the code there so my problem is clearly understood.

What I need is an strategy - a way of attacking this. I know some basic physics, but I'm no expert. For example, does this problem have a name? That sort of thing.

Thanks a lot.

EDIT: Beta provided a valid strategy for this and Judge kindly implemented it directly in LÖVE, in the comments.

EDIT2: After more googling I also found openSteer. It's on C++, but it does what I pretended. It will probably be helpful to anyone reaching this question.

A: 

Your angle is the Inverse Tangent the Opposite/Adjacent

So angle = InvTan(VY/VX)

No sure what your are talking about concerning wanting to drift??

MindStalker
Mmm thank you, but I already had figured that one out. I was talking about a different problem here.
egarcia
+1  A: 

To just get from the current position to the destination with an initial velocity, then apply thrust along the normalized difference between the shortest path and the current velocity. You don't actually need the angle.

-- shortest path minus initial velocity
dx,dy = x0 - x - vx, y0 - y - vy

-- normalize the direction vector
magnitude = sqrt(dx*dx + dy*dy)
dx,dy = dx/magnitude, dy/mangitude

-- apply the thrust in the direction we just calculated
self:applyImpulse(thrust*dx, thrust*dy)

Note that this does not take the target velocity into account because that gets extremely complicated.

I have a very small Lua module for handling 2D vectors in this paste bin. You are welcome to use it. The code above would reduce to:

d = destination - position - velocity
d:normalize()
d = d * thrust
self:applyImpulse(d.x, d.y)
Judge Maygarden
"You don't actually need the angle." Except, presumably, within the game, in order to have the ship aim the thrust at the correct direction vector, he'll need to translate that into an angle anyway. (Most ships can't acclerate in any direction...only along their primary axis).
Beska
Well, getting the angle from the direction vector is a trivial operation (e.g. acos(dx), asin(dy), atan2(dx,dy)). However, there is no real need for it in his example since he immediately converts it to a direction vector using trig functions.
Judge Maygarden
@Beska: actually it's pretty easy for most spacecraft to rotate, just by spinning internal flywheels. No need to expend reaction mass, and arbitrarily low net energy expenditure.
Beta
The final velocity was actually the "interesting" part. I had already figured out your algorithm. But I had ships attempting to land on spaceports at half the speed of sound :D - so I really needed to decelerate them first. Thanks anyway for your answer.
egarcia
It is an "interesting" problem. Good luck and I'd love to hear about your progress!
Judge Maygarden
+5  A: 
Beta
Right, the full answer at least requires a state machine unless you are some kind of math god.
Judge Maygarden
Hi there, thanks for the extense answer! The problem is actually *more* complicated than this - involves the ship "orientating itself" with torques in a finite time before being able to thrust in the proper direction. But this is the first 'bite' I was looking for. And now I can google for "motion planning" :D.
egarcia
@egarcia Just for fun, I made a LOVE2D demo of the method Beta describes. It works pretty well. Download it here: (http://www.mediafire.com/file/m2tjdknwhwd/spacenav.love). Click and drag to set new target positions/velocities. Be careful sending the blue dot way off the screen with large final velocities. I didn't handle that at all. ;)
Judge Maygarden
Judge, you just blew my mind. Thanks for putting this up!
egarcia
A: 

Are you expelling fuel? Your mass will change with time if you are.

Thrust is a reactive force. It's the rate of change of mass, times the speed of the exhaust relative to the spaceship.

Do you have external forces? If you do, these need to enter into your impulse calculation.

Let's assume a magical thrust with no mass being expelled, and no external forces.

Impulse has units of momentum. It's the integral of a force over time.

First off, you'll need to figure out exactly what the API calls "thrust" and impulse. If you're feeding it a thrust multiplied by a scalar (number), then applyImpulse has to do something else to your input to be able to use it as an impulse, because the units don't match up.

Assuming your "thrust" is a force, then you multiply that thrust by the time interval (1/30 second) to get the impulse, and break out the components.

Don't know if I'm answering your question, but hopefully that helps you to understand the physics a bit.

John at CashCommons
Hi there! Thrust is something I invented. Is the magnitude of the impulse. I thought it was clear on the code, maybe I should have explained it more. "Impulses" here means "discrete appliances of force applied on a given moment". And you were right about not assuming fuel consumption - It would not add fun to the game and would complicate the calculus. Thanks for answering.
egarcia
A: 

It's easier to think about if you separate the ship's velocity into components, parallel and perpendicular to the target velocity vector.

Considering along the perpendicular axis, the ship wants to come in line with the target position as soon as possible, and then stay there.

Along the parallel axis, it should be accelerating in whatever direction will bring it close to the target velocity. (Obviously if that acceleration takes it away from the target point, you'll need to decide what to do. Fly past the point and then double-back?)

I would deal with the two of them separately, and probably perpendicular first. Once it's working, and if that doesn't prove nice enough, you can start to think about if there are ways to get the ship to fire intelligent angles between perpendicular and parallel.

(EDIT: also, I forgot to mention, this will take some adjustment to deal with the scenario where you are offset a lot in the perpendicular direction but not much in the parallel direction. The important lesson here is to take the components, which gives you useful numbers on which to base a decision.)

Chris Burt-Brown
Sorry, but your answer doesn't help me much - I don't see why splitting the velocity into "two components" is going to help me. But thanks for answering anyway.
egarcia
The point about my answer is that you are trying to solve one complicated two-dimensional problem, whereas I am suggesting solving two simpler one-dimensional problems.
Chris Burt-Brown
+3  A: 

In the absence of additional info, we can assume there are 3 forces acting upon the spaceship and eventually dictating its trajectory:

  • "impulses" : [user/program-controlled] force.
    The user (or program) appear to have full control over this, i.e. it controls the direction of the impulse and its thrust (probably within a 0-to-max range)
  • some external force: call it gravity, whatever...
    Such force could be driven by several sources but we're just interested in the resulting combined force: at a given time and space this external force acts upon the ship with a given strengh and direction. The user/program has no control over these.
  • inertia: this is related to the ship's current velocity and direction. This force generally causes the ship to continue in its current direction at its current speed. There may be other [space-age] parameters controlling the inertia but generally, it is proportional to both velocity and to the ship's mass (Intuitively, it will be easier to bring a ship to a stop if its current velocity is smaller and/or if its mass is smaller)

Apparently the user/program only controls (within limits) the first force.
It is unclear, from the question, whether the problem at hand is:

  • [Problem A] to write a program which discovers the dynamics of the system (and/or adapts to changes these dynamics).
    or..
  • [Problem B] to suggest a model -a formula- which can be used to compute the combined force eventually applied to the ship: the "weighed" sum of the user-controlled impulse and the other two system/physics-driven forces.

The latter question, Problem B, is more readily and succinctly explained, so let's suggest the following model:

Constant Parameters:
  ExternalForceX   = strength of the external force in the X direction
  ExternalForceY   = id. Y direction
  MassOfShip       = coeficient controlling 
Variable Parameters:
  ImpulseAngle     = direction of impulse
  ImpulseThrust    = force of thrust
Formula:
  Vx[new] = (cos(ImpulseAngle) * ImpulseThrust) + ExternalForceX  + (MassOfShip * Vx[current])
  Vy[new] = (sin(ImpulseAngle) * ImpulseThrust) + ExternalForceY  + (MassOfShip * Vy[current])

Note that the above model assumes a constant External force (constant both in terms of its strength and direction); that is: akin to that of a gravitational field relatively distant from the area displayed (just like say the Earth gravity, considered within the span of a football field). If the scale of the displayed area is big relative to the source(s) of external forces, the middle term of the formulas above should then be modified to include: a trigonometric factor based on the angle between the center of the source and the current position and/or a [reversely] proportional factor based on the distance between the center of the source and the current position.
Similarly, the Ship's mass is assumed to remain constant, it could well be a variable, based say on the mass of the Ship when empty, to which the weight of fuel is removed/added as the game progresses.

Now... All the above assume that the dynamics of the system are controlled by the game designer: essentially choosing a set of values for the parameter mentioned and possibly adding a bit of complexity in the math of the formula (and also ensuring proper scaling to generally "keep" the ship within the display area).

What if instead, the system dynamics were readily programmed into the game (and assumed to be hidden/random), and the task at hand is to write a program which will progressively decide the direction and thrust value of the impulses to drive the ship to its targeted destination, in a way that its velocity at the target be as close as possible to getTargetVelocity()? This is the "Problem A".

This type of problem can be tackled with a PID Controller. In a nuthell, such a controller "decides" which amount of action (in this game's case = which impulse angle and amount of thrust to apply), based on three, weighed, factors, loosely defined below:

  • how far-off we are the current values from "set point": this is the P=Proportional part of PID
  • how fast are we approaching the "set point": this is the D=Derivative part of PID
  • how long and how much have we been away from the "set point": this is the I=Intergral part of PID

A less sophisticated controller could for example only use the proportional factor. This would result in oscillating, sometimes with much amplitude on either side of the set point ("I'm X units away from where I'm supposed to be: let me yank the steering wheel and press on gas"). Such overshooting of the set point are tempered by the Derivative factor ("Yeah, I'm still not where I'm supposed to be but the progress I made since the last time I check is very big: better slow down a bit"). Finally the Integral part takes into account the fact that all things being equal with regards to the combined Proportional and Derivative part, a smaller or bigger action would be appropriate depending on whether we've been "off-track" for a long time or not and of much off track we've been all this time (eg. "Lately we've been tracking rather close to where we're supposed to be, no point in making rash moves")

We can discuss the details implementing PID controllers for the specific needs of the space ship game, if that is effectively what is required. The idea was to provide a flavor of what can be done.

mjv
Thanks for your extensive response. It's funny that you mention "oscillating" - I've already seen this happening on my tests. I'll certainly look at those PIDs you mention. Unfortunately, I can only mark one answer as valid, Beta's response seems a bit more accurate useful ("motion planning" is exactly the term I was looking for). So I'll give you +1 .Thanks a lot!
egarcia
@egarcia: no need to apologize for only accepting one answer ;-) "motion planning" algorithms will effectively help you, _provided_ that the dynamics of the system are constant (or for the least deterministic). A PID controller would help even if the dynamics of the system are stochastic (or also if they are deterministic but not so readily tractable). Whether with MP or PID, the problem you are trying to solve is difficult because of the requirement of a particular velocity and direction upon passing the target point: can't use line between start point and target as an ideal trajectory...
mjv