This Exercise Set has been submitted for peer review, but it has not yet been accepted for publication in the PICUP collection.

Planetoids game (similar to asteroids)

Developed by Chris Orban

This lab will guide you through coding up a web-based implementation of the classic video game asteroids. Unfortunately, tablets will probably not work very well unless you have an external keyboard. This exercise will use a programming language called [p5.js](http://p5js.org) that is very similar to C and C++ programming. (Note: If you are familiar with C or C++ the main difference you will see is that there is no main() function and instead the draw() function serves this role.) **Importantly, this exercise can be completed using any computer or chromebook without downloading any software!** In the classic game of Asteroids, there is a little ship that flies around in space, very far away from stars and planets so that the gravitational acceleration is zero. This exercise is designed for an algebra-based physics class at the college or high school level. It may also be useful for calculus-based physics for non-majors (e.g. engineering & science majors). This exercise is part of a series of exercises developed by Prof. Chris Orban. The exercise after this one is called [Lunar Descent](http://www.compadre.org/PICUP/exercises/exercise.cfm?I=246&A=LunarDescent) in which gravity is added to the simulation. You can also jump ahead to the [Planetoids with momentum! exercise](http://www.compadre.org/PICUP/exercises/exercise.cfm?I=248&A=PlanetoidsMomentum) or the [Planetoids with torque! exercise](http://www.compadre.org/PICUP/exercises/exercise.cfm?I=249&A=PlanetoidsTorque) after completing this one. There are pre-and-post assessment questions associated with this exercise (not available here) that are being used in an educational research study. If interested to collaborate on that study please e-mail Prof. Chris Orban (orban@physics.osu.edu). The first paper from this study [is available at this link](https://arxiv.org/abs/1701.01867), the second paper which discusses the electromagnetism exercises [is available at this link](https://arxiv.org/abs/1707.00185)
Subject Area Mechanics
Levels High School and First Year
Learning Objectives
Students will be able to: 1. Create an interactive model of a ship traveling in free space 2. Understand how to convert a simple 1D code into a 2D code 3. Understand how force, velocity and acceleration vectors relate to the motion of a ship traveling in free space
Time to Complete 60 min

Step 1. Play around with a 1-dimensional version of Asteroids

Click on [this link to the 1D version](http://www.physics.ohio-state.edu/~orban/physics_coding/planetoids1d_v1/planetoids.html) of the spaceship from asteroids. Push up arrow to see the rocket accelerate. Unfortunately right now the ship can only accelerate in one direction. We will change this step-by-step to make the behavior more similar to the classic asteroids game. If the example doesn't work tell the instructor. This is the code used to move the ship around in the 1D version. Take a close look at the code and try to get an idea of what each part does:
function draw() {

    // Update velocities
    vx += deltaVx;

    // Update location
    x += vx*dt;

    // velocity is unchanged if there are no forces
    deltaVx = 0;

    if (keyIsDown(LEFT_ARROW)) {
        theta += 0.0;
    }
    if (keyIsDown(RIGHT_ARROW)) {
        theta += 0.0;
    }
    if (keyIsDown(UP_ARROW)) {
        // Rockets on!
        accelx = Fthrust*cos(theta)/mass;
        deltaVx = accelx*dt;
    } 
    if (keyIsDown(DOWN_ARROW)) {
        // Do nothing
    } 
    if (keyIsPressed && key == ' '){ //spacebar
       // Do nothing!
    }
  
    // Draw ship and other stuff
    display();

} // end draw()

Step 2. Try out the 1D planetoids code in an editor

[Click on this link to open the 1D planetoids code in a p5.js editor](https://alpha.editor.p5js.org/ChrisOrban/sketches/SJyV-PekZ) Press play there to run the code. It should look the same as it did with the [link you were given in Step 1](http://www.physics.ohio-state.edu/~orban/physics_coding/planetoids1d_v1/planetoids.html)

Very Important: Sign up for an account! Then click "Duplicate" so you can have your own version of the code!!!

Step 3. Edit the source code to let the ship rotate!

After you click duplicate! to make sure that you're working on your own version of the code, change these lines of code:
    if (keyIsDown(LEFT_ARROW)) {
        theta += 0.0;
    } else if (keyIsDown(RIGHT_ARROW)) {
        theta += -0.0;
to look like this:
    if (keyIsDown(LEFT_ARROW)) {
        theta += 0.1;
    } else if (keyIsDown(RIGHT_ARROW)) {
        theta += -0.1;
The asteroids game is now set up so so that only the x-component of the thrust is what accelerates the ship. Notice that allowing the ship to rotate means that we can speed up and slow down the ship because we can rotate the rocket and apply a force that is opposite to the velocity vector. Our asteroids game is already a lot more fun! For reference, [the game should now behave like this](http://www.physics.ohio-state.edu/~orban/physics_coding/planetoids1d_v2/planetoids.html)

Step 4. Enable multi-dimensional space travel (i.e. let the ship move in the y direction too)

Now take the code you've written and modify it so that the ship can move in the y direction. It will take a few different changes to get it to work.

Step 4a. Change the "Update location" section

Look at the "Update location" section. Right now it looks like this:
// Update location
x += vx*dt;
As you can see, only the x position is updated. The y position is not updated. Change the "Update location" section to this:
// Update location
x += vx*dt;
y += vy*dt;

Step 4.b. Change the "Update velocities" section

If you did step 4a correctly, we can now update both the x position and the y position, but only if $v_x$ and $v_y$ are non-zero! This will only happen if we change the "Update velocities" section so that both vx and vy are updated. Change this:
\\ Update velocities
vx += deltaVx;
to this:
\\ Update velocities
vx += deltaVx;
vy += deltaVy;

Step 4.c. Objects in motion move in a straight line unless acted on by a force

Newton realized that objects move in a straight line with constant velocity if there are no forces acting on the object. For our computer program, we need to make sure that the velocity only changes when we push buttons on the keyboard. If we don't push any buttons then the change in velocity ($\Delta v_x$ and $\Delta v_y$) had better be zero. This is the logic behind this part of the code:
    // velocity is unchanged if there are no forces
    deltaVx = 0;
Change this to make sure deltaVy is set to zero too:
    // velocity is unchanged if there are no forces
    deltaVx = 0;
    deltaVy = 0;
This is an important step because if you do the next step correctly, but you forget to do this the ship will accelerate uncontrollably.

Step 4.d. Make sure that acceleration works in the y-direction

If you've done all the steps up to this point correctly, the ship still won't move in the y direction because we haven't told the ship how to accelerate in the y direction when the thrusters are turned on. Nowhere in the program do we set deltaVy equal to anything except zero! Look closely at this part of the code:
    if (keyIsDown(UP_ARROW)) {
        // Rockets on!
        accelx = Fthrust*cos(theta)/mass;
        deltaVx = accelx*dt;
    }
You'll need to change this to something like this:
    if (keyIsDown(UP_ARROW)) {
        // Rockets on!
        accelx = Fthrust*cos(theta)/mass;
        deltaVx = accelx*dt;
        accely = ????
        deltaVy = accely*dt;
    }
It's your job to replace the ???? with something that actually gives the correct acceleration in the y direction. (Hint: it is very similar to the code for accelx but the trig function might be different! Should you use cosine, sine or tangent for the trig function? If you're not sure just try one and see what happens!)

Step 5. Check that everything works as expected!

If you make all these changes [your code should behave like this](http://www.physics.ohio-state.edu/~orban/physics_coding/planetoids1d_v2/planetoids.html) and your ship should be able to move in 2 dimensions! Potential pitfall: Which trig function did you use to determine the y-component acceleration?

Step 6. Find the best combination of thrust and mass to survive!

If your code behaves as expected, then take all your modifications to the 1D code and [add them to this version of the code which includes planetoids!](http://alpha.editor.p5js.org/ChrisOrban/sketches/S1UesXHWZ)

Change the values for Fthrust and the mass until you find the best combination to fly around the planetoids!

Challenges: Choose one

Option: Add Reverse thrusters

This is one of the easier challenges. Notice that your code has a section for when you press the down arrow:
    if (keyIsDown(DOWN_ARROW)) {
        // Do nothing                                                           
    }
Where it says "Do nothing" how would you add code to fire the thrusters in reverse? Hint: You want to accelerate in the opposite direction of the acceleration you get when the thrusters are turned on.

Option: Add a projectile to the game

You can add another if statement to check to see if you've pressed the spacebar:
    if (keyIsPressed && key == ' ') { // spacebar is pressed
      // Do nothing
    } 
How would you modify the code so that the spacebar shoots a projectile from the nose of the ship? Add two new float variables called xprojectile and yprojectile to the beginning of the program and use the "drawPoint" function to show the position of the projectile:
drawPoint(xprojectile,yprojectile);
Advice: Place this function just after display(); so that it is drawn every time but set xprojectile and y projectile to zero initially so that the point is drawn at the top left corner of the grid and you can't see it. When the spacebar is pressed set the xprojectile and yprojectile equal to the position of the ship. That at least will put a dot on the screen where the ship is. How would you make it move?

How to get full credit on this assignment!!!

1. Complete steps 1-4 and make absolutely sure that the ship can turn and move in two dimensions Make sure your program [behaves exactly like it does at this link](http://www.physics.ohio-state.edu/~orban/physics_coding/planetoids1d_v2/planetoids.html) to be sure you did steps 1-4 correctly 2. Complete one of the challenges Most people choose the reverse thrusters, which is probably the easiest 3. Find the best combination of Fthrust and mass to survive! This requires modifying [a version of the code that includes planetoids](http://alpha.editor.p5js.org/ChrisOrban/sketches/S1UesXHWZ) 4. Submit your code before the deadline Talk to your teacher about where to submit the code

Download Options

Credits and Licensing

The instructor materials are ©2017 Chris Orban.

The exercises are released under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 license

Creative Commons Attribution-NonCommercial-ShareAlike 4.0 license