VPython
Background
This exercise invites you to explore a variant of python, called vpython, which is:
- Object-oriented (everything is organized via objects and classes),
- Web-based (everything runs in your browser), and
- Graphical (you’ll build and program the behavior of 3D models).
The goal of this lab is to explore vpython in order to understand—and extend—a 3D interaction. If you enjoy working with vpython, you might consider a vpython-based final project in the upcoming weeks, as well. In that final project, the goal could be to create a game or interaction of your own design.
Documentation
These links may be useful to have in one place:
- Documentation for each object, the scene, and other
vpythonfeatures. vpythonexamples:
Remember that these links are here, but for now let’s begin with an example…
Getting Started
Then, run it. It may pause for a second, but should eventually open up a web browser with a 3D box! Make sure you can
- Rotate the cube (right mouse button)
- Zoom in and out from the cube (scroll wheel or two-finger drag)
Task 1: Play around with the three components of the color…
- They’re in (red, green, blue) order
- They’re between
0.0and1.0 - They need to be specified as a vector (note the
vector(r, g, b)constructor: inpython, everything is an object…)
Task 2: Play around with the three components of the size…
Grab the size parameter and place it (after a comma) into the creation of the box, i.e.
Try it out! They are in (length, height, width) order. Again, in a vector constructor…
Task 3: Play around with the three components of the axis…
Grab the axis parameter and place it (after a comma) into the creation of the box, i.e.
Try it out! They are in (x, y, z) order. The size parameter of length is along the axis.
Not required: you can specify how width and height are defined via the up parameter.
The documentation for all of this is at the GlowScript reference for box()
Next, you’ll try a starting animation with a bit of physics…
Physics Simulation in vpython
Create a new Python file and paste in the following code (it’s lengthy!):
Run it!
Then, match its behavior to the pieces of the code—look over the source, which introduces:
- Some global scene and background variables (based on scene).
- Two objects, ground and ball, of class box and sphere, respectively.
- Some variables to help the animation.
- The
while Trueanimation loop, or “event loop”. - Some physics (updates and collision checks).
- Two event-handling functions: one for key presses, one for mouse clicks.
- Hit some keys in the 3D drawing canvas to see what prints…
- One additional function (that generates a random color).
Next, in order to feel comfortable and more deeply understand each part of this animation, make these changes to the code and try them out:
Task 1: [Setup] Change the background color and canvas size
- Change the value of
scene.backgroundto change the background color.- Neat trick: the expression
0.42*vector(1, 1, 1)is a fast way to getvector(0.42, 0.42, 0.42), which is dark gray…
- Neat trick: the expression
- Change the value of
scene.widthandscene.heightto adjust your canvas size. - Try it all out! Errors? Debugging is inevitable…
- Sometimes, frustratingly, the browser python simply ignores errors—those are trickier to debug!
- Test one change at a time—test often!
Task 2: [The objects] Change the moving object from class sphere to something else…
- Change the class of the moving object from
spheretobox.- Don’t change the name of the object (that way the “downstream” code will be ok).
- Try two or more other shapes!
- The full list is here: http://www.glowscript.org/docs/GlowScriptDocs/primitives.html
- From that page’s left-hand pulldown menu, you can see the details on each shape, i.e., each class …
- Feel free to change the initial color, starting position, starting velocity, axis, size, etc.
- Test one change at a time—test often (we might just keep this note around for each task!).
Task 3: [Physics updating] Change the universe! (Well, change physics, at least…)
- Don’t change (for now) the set-up variables before the animation loop (“physics loop” or “event loop”)
RATEis the number of frames rendered per second (at least with the browser’s best effort).scene.autoscale = Falsemeans you need to manually zoom (Trueautomatically zooms, which is often more annoying than helpful).scene.forwardis the viewing vector—a good default, for now.originis a point of interest, so we’ve given it a name (totally optional, but helpful).
- DO add friction!
- UNDER the physics-update line, which calculates “distance = rate*time” by writing
ball.pos = ball.pos + ball.vel*dt - Add a second line that multiplies the
ball.velvector:ball.vel = ball.vel * 0.98 - Try it! You’ll see you’ve programmed friction into the world!
- UNDER the physics-update line, which calculates “distance = rate*time” by writing
- Reverse it! Try
ball.vel = ball.vel * 1.05for reverse friction.- It’s nice being able to program your own physics!
- You may want to remove friction altogether as you continue exploring—it’s up to you…
- Test one change at a time—test often!
Task 4: [Collision code] Create collisions and interactions…
- Next, read over and change the collision-defining part of the code…
- The
mag()function computes the total magnitude (length) of a vector via the Pythagorean theorem (aka “Euclidean distance”)mag(ball.pos - origin)thus computes the total distance fromball.posto theorigin- Change the number it’s comparing to from
10.0to20.0—try it!
- Try resetting the ball to a different starting point.
- Try making the reset velocity larger.
- Try commenting out the
ball.vel.y = 0.0line- As always, test one change at a time—test often!
Task 5: [Other Functions] Look over the event-handling and other functions at top…
- Read over the other three functions
- Note that
keydown_funuses ball without passing it in!- The ball object is a global variable, which means it is automatically accessible to all functions defined after it has been defined.
- Try changing the printing inside
keydown_fun—in any way you’d like, to show you have full control here…- Try changing that printing line so that you see the newly-defined color’s
r,g,bcomponents…
- Try changing that printing line so that you see the newly-defined color’s
- The other two functions are probably OK as-is, but if you’d like to test different things out, of course, feel free to do so…
- As always, test one change at a timei—test often!
All right! You have a constructive sense of how vpython supports physics and physical interactions…
Next, you’ll build an interaction (or game…) of your own. But, let’s begin from a slightly more sophisticated starting point in the next section…
Building Your Own Game with vpython
So, create a new program and paste in the following code (again, it’s long):
Phew! This is a larger chunk of code. Let’s look at%G—%@and change—this code piece-by-piece, in order to build an understanding of it.
Task 1: [The objects] Read over the object-creation lines and try it out…
- For now, skip the overall
scenevariables and themake_alienfunction at the top… We’ll come back to those. - Scroll to the object-creation lines:
groundandball, as beforewallAandwallBare new boxes, with distinct hues (amber and blue)alienandalien2are new objects that are composites of other objects—cool! We’ll handle compositing later…
- Try the game, using the arrows (or ijkl or wasd) to impart velocity on the ball
- Note that the arrows correspond to punctuation marks—if your keyboard is different, use the letters instead (ijkl or wasd)
- The
alienis moving under computer control, but theballis under your control - The goal of the game is to reach the
alienwith theball—if you do, thealienascends and prints a message…- That’s it! Yes, this game needs work!
So, let’s work on it…
Task 2: [More walls] Creating your own walls and collisions…
- Your challenge here is to read over the wall-creation code:
- Figure out how the wall-creation works.
- Then, create two more walls to finish the “table” or “corral”.
- I’d recommend using distinctive colors for each!
- Then, read over the wall-collision code:
- Figure out how the wall-collision code works.
- Note that the ball’s position is corrected so that it’s no longer “beyond the wall” each time.
- This is important—if uncorrected, the ball can get “stuck” inside the wall…
- Then, add collisions to your two new walls.
- Figure out how the wall-collision code works.
- Try it! Now, the game will play on its own…
- The ball will bounce around the corral and eventually encounter the alien…
- Test often!
- This becomes more and more important as the game gets larger and larger.
- Copy your whole program to a file on your desktop (using your text editor, e.g., vscode).
- The problem with Web-editing like this is that there’s no “undo”—aargh!
- Having a working copy to return to is vital.
Task 3: [Your own helper function] Creating your own corral-colliding function…
- Your challenge here is to take your wall-colliding code and get comfortable making that into its own function.
- Since there are four walls, making a corral, let’s call it corral-colliding…
- This yields a MAJOR advantage: you’ll have ONE corral-colliding function, which EVERY moving object can use!
- Notice that your corral-colliding lines use the ball variable to check for collisions with the walls
- We’re going to make that an argument to the function instead!
- To do this, cut your corral-colliding code (probably four if statements with their bodies) and…
- Paste them into the “other functions” section at the bottom of the file.
- Add this function-signature line above them:
def corral_collide(ball):
- For completeness, add this docstring as well:
- THEN, add the line
corral_collide(ball)back where you had cut the original lines.- That line will call the function each time through the animation loop, as needed.
- You can now add the line
corral_collide(alien), too—try it!. - To see it working, remove or comment-out the block of code that resets the
alien.- It has a comment:
# if the alien ventures too far, restart randomly
- It has a comment:
- Both the alien and the ball should now bounce around…yay!
Finally, we can start on…
The Exercise
You’ll be making a 3D do-it-yourself interaction or game!
- You have a palette of 3D “object paints” and a canvas with physics, collisions, and keypresses…
- From here, this lab problem asks you to make changes to this starter code to build your own game or interaction.
- What the game does and how it looks are entirely up to you—but you should include at least TWO of these things (or more—this can become your final project, if you’d like):
- Add one or more additional non-moving objects in the “playing field” (trees, spaceships, etc. are all fair game to build…).
- Create at least one new self-moving object (more aliens—or other things?!).
- Add one additional interaction between the new objects and the user-controlled object (collisions or bouncing, as one example).
- Expand the existing
compoundobject or add a new one (see below) (treating multiple objects as a single whole). - Change the user-controlled object (or add another user-controlled object, along with a way to switch between them…)
And, it is ever so: test often! As often as you’re willing, copy your whole program to a file on your desktop (using your text editor, i.e., vscode).
The problem with Web-editing like this is that there’s no “undo” :(
Compound objects
If you’d like to try building or extending your own composite (or
compound) objects, look over themake_alienfunction near the top of the file…It creates several pieces in their own coordinate system.
It makes a list of those pieces and then calls
com_alien = compound(alien_objects, pos = starting_position).- This creates an object named
com_alien, which is of class (or type)compound. - This sticks all of the objects together and gives them a single existence—they can no longer be independently manipulated, but the whole thing can be…
- This creates an object named
To do: Make your own character!
- It could be a variation on this one (a third eye, perhaps? or even more detail…).
- It could be something completely different…
Notice that by passing in the
starting_positionvector, the single function can create as many different composite objects as you’d like…- This technique is demonstrated by the two aliens in the original…
Other helpful functions…
Below is a wall_collide(wall, object) function for walls at any angle in the x-z plane.
It ignores the y components, though you could adapt it to handle those, as well, if you wish.