I am writing a small game where a sea vessel (like a battleship) can be moved in a 2D place based on orders that it receives. I wanted to know if someone can help direct me to a post or example code that will help me move a ship from one location to another based on the speed and new vector.
So, if I had a ship that is moving in a south westerly direction (say 120 degrees) and it receives new orders to turn to a new vector of 020 degrees, how can I calculate the turn. I don’t want it to just turn on a dime and head in the new direction. I want it to make the wide turn (as if it were in water) and then when it reaches the new vector, start heading in that direction.
Any help would be appreciated.
3
You’re travelling in a particular direction at a particular speed. So in a xy coordinate system, you’re probably doing something like:
velocity_x = speed*cos(angle)
velocity_y = -speed*sin(angle)
x += velocity_x*t
y += velocity_y*t
You now want to go at a different angle, i.e. a different velocity. A difference in velocities is an acceleration
. It might be easier to consider this as a constant radians/s2 rather than anything more ‘realistic’. So perhaps something like the followng:
acceleration = a_constant // for simplicity
angle = start_angle
while angle < end_angle // depending on clockwise or anticlockwise turn
angle += acceleration*t
velocity_x = speed*cos(angle)
velocity_y = -speed*sin(angle)
x += velocity_x*t
y += velocity_y*t
This is a standard approach; track the ship using is speed and heading and change those as required. Make the x and y velocity a function of those.
class Ship
{
double x = 0;
double y = 0;
double speed = 15; // m/s;
double heading = 120;
double plannedHeading = 0;
double turnRate = 3; // deg /s
public Ship()
{
plannedHeading = heading;
}
void update(double dt)
{
x += dt * getVx();
y += dt * getVy();
if (heading != plannedHeading)
{
computeTurn(dt);
}
}
void computeTurn(double dt)
{
double dh = plannedHeading - heading;
if (dh < -180)
dh += 360;
if (dh > 180)
dh -= 360;
if (Math.Abs(dh) < turnRate * dt)
heading = plannedHeading;
else
{
int dir = 1;
if (dh < 0)
dir = -1;
heading += turnRate * dt* dir;
}
}
public void turnTo(double newHeading)
{
plannedHeading = newHeading;
}
public double getVx()
{
return speed * Math.Acos(heading * Math.PI / 180);
}
public double getVy()
{
return speed * Math.Asin(heading * Math.PI / 180);
}
}
2
Keep the heading in an angular vector and increment the angle over time until it reaches the new angle. An angular vector is simply a vector kept in angular form. So you keep a field that contains the angle of the ship. Over time (at regular intervals, with changes as a function of elapsed time), modify this angle until it reaches the new heading.
Do not store the angular vector as a regular vector using x and y components, as it will degrade due to floating-point inaccuracies over time.
1