## Learning and Applying Mathematics using Computing

### Catch My Drift

This post is about implementing drifting movement (a la asteroids), and draws together several previous posts.

There are various simple movement schemes that you can implement in games. We’ve used one in our previous posts: moving at a fixed speed (with steering). Another is what I will call asteroids-style movement: you have a persistent velocity (or “drift”), and you can apply thrust in a particular direction to change the velocity. It’s hard to describe it simply in text, so the best way to get an idea of what I’m talking about is to go have a play with the scenario.

In this post, we will implement drifting. To do this, we must create a variable to hold the current speed in the X direction, and the current speed in the Y direction. Each frame we add the current speeds onto the current position.

The key aspect of implementing drift-style movement is that when we press a key to move, instead of adding some amount to the current position, we add some amount (known as acceleration) to the current speed, which in turn will be added to the current position in each of the future frames. We’ve already seen this technique in the previous post on falling, so we can form a rough skeleton of our code:

```    private double speedX;
private double speedY;

public void act()
{
doTurn();

doMove();
}

private void doMove()
{
if (Greenfoot.isKeyDown("up"))
{
setImage("rocket.png");

speedX = speedX + ???;
speedY = speedY + ???;
}
else
{
setImage("rocket_nothrust.png");
}

setLocation(getX() + (int)speedX, getY() + (int)speedY);
}
```

(We’ll additionally use the doTurn method from our turning example, and also the world-wrapping code from our world-wrapping example.)

So we have persistent variables for speedX and speedY, declared as members of our Spaceship class. We add these speeds to our position each frame, on the last line of the code above. We also have some code to change the image of the rocket when we are accelerating/drifting. The bit that still needs filling in is how to adjust the speed each frame.

We want to add an appropriate acceleration to our speed, based on which direction we’re facing. We want to accelerate a certain amount in the direction we are pointing. This is exactly the same principle as an earlier post, where we wanted to move a certain amount in the direction we are pointing. The only difference is that instead of moving, we add to our speed:

```            double radians = Math.toRadians(getRotation());
double moveSpeed = 0.1;

double accX = Math.cos(radians) * moveSpeed;
double accY = Math.sin(radians) * moveSpeed;

speedX = speedX + accX;
speedY = speedY + accY;
```

You can have a play with the finished scenario, or view its full source code in Greenfoot. You may notice that its speed can increase to unlimited amounts — we will fix that in a forthcoming post.