{ "cells": [ { "cell_type": "markdown", "id": "012aa264", "metadata": {}, "source": [ "# animation\n", "\n", "While py5 is perfectly well-suited for creating still images as its visual output, where programming art begins to far outpace manually produced art is in the realms of animation and movement. Even if you \"only\" had to draw one image and slowly slide it across a background surface, photographing each different position one at a time, animating something by hand is a tedious task. In comparison, animating images in py5 is easy - once you understand the principles behind movement and animation in general.\n", "\n", "The way the brain perceives motion in general is fairly straightforward, though there are a lot of different factors that can enhance the accuracy of that perception (or the illusion, in the case of animation). Your retina passes an image to your brain around ten times per second. Whether you perceive something as moving or still, then, is reliant on whether its position is changing compared to that rate. One of the founders of Gestalt school of psychology, Max Wertheimer, found in 1912 that perception of smooth movement between two images of shapes in different locations was highly dependent on the rate at which these images were shown. Another psychologist, Friedrich Kenkel, called this particular illusion - two separate figures, interpreted as one figure moving from one place to the next - *Beta movement*. Screens that update information relatively slowly, like news tickers and LED displays, rely heavily on Beta movement for animation. Generally, for the illusion to work, images are displayed at around ten to twelve frames per second. However, you can start observing the effects at much lower frame rates. \n", "\n", "\n", "\n", "In the image above, you can see the circles are numbered. If you displayed just circle 1 for four seconds, and then just circle 5 for four seconds, most people would see this as unrelated images. This is a very low frame rate, 0.25 FPS. \n", "\n", "\n", "\n", "Let's speed this up a bit. If each frame appears for 0.4 seconds instead of 4 seconds, we're operating at 2.5 FPS instead of 0.25. You can likely see that the circle appears to bounce back and forth between the two points.\n", "\n", "\n", "\n", "By further increasing the FPS to 12 frames per second, you begin to reach the bounds of the Beta movement illusion - the circle is either moving quite quickly between these two points, or there are two circles flickering together.\n", "\n", "\n", "\n", "We can observe a few more illusions related to this using the entire ring of circles. This animation runs at one frame per second. \n", "\n", "\n", "\n", "If you watch the above animation, you may see one circle as \"jumping\" into the gap on each frame!\n", "\n", "Meanwhile, in this much faster animation (25 FPS), it looks as if that gap is actually its own object, moving around and obscuring each circle:\n", "\n", "\n", "\n", "This illusion is known as the *phi phenomenon*. With a slightly better understanding of how adjusting framerate can change the perception of animation, let's move on to how this all works in py5.\n", "\n", "## animation functions\n", "\n", "To use animation in py5 (as well as a handful of other nifty features), you have to take advantage of two built-in functions that define the behavior of whole blocks of code: `setup()` and `draw()`. Other tutorials do not always use these functions - coding in py5 without using these is referred to as *static* mode, since the sketches it creates will have still (static) visuals. Py5bot is set up to run these sorts of sketches by default. A static sketch might begin with some code like this, to set up the various unchanging qualities of the sketch:" ] }, { "cell_type": "markdown", "id": "f8475155", "metadata": {}, "source": [ "```python\n", "size(500,500)\n", "background('#004477')\n", "no_fill()\n", "stroke('#FFFFFF')\n", "stroke_weight(3)\n", "```\n", "\n", "It's no surprise, then, that this is the sort of code you execute in a `setup()` function. Like many other types of code blocks (such as those you would use for *if* statements), indenting is used to keep all this `setup()` code running together. In some development environments (like on this documentation website), you may also need to include a `run_sketch()` line at the bottom of your sketch. This line will be included in all code snippets here, so that they can be run using live code." ] }, { "cell_type": "code", "execution_count": 9, "id": "d48a0fdc", "metadata": {}, "outputs": [], "source": [ "def setup():\n", " size(500,500)\n", " background('#004477')\n", " no_fill()\n", " stroke('#FFFFFF')\n", " stroke_weight(3)\n", "\n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "dbe846c2", "metadata": {}, "source": [ "Any code in that block following `def setup():` is run once, when the sketch begins. \n", "\n", "This `setup()` function becomes very powerful when you use it with `draw()`. Unlike `setup()`, which is run once, `draw()` is run every frame! By default, sketches run at 60 frames per second, but this number may reduce if a lot of heavy-duty animation is running on screen. You can use a built-in variable, `frame_rate`, to see how many frames have advanced since the start of the sketch. Let's use this inside of another block, for `draw()`, to see how it works." ] }, { "cell_type": "code", "execution_count": 10, "id": "4b0f8b56", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n", "10\n", "11\n", "12\n", "13\n", "14\n", "15\n", "16\n", "17\n", "18\n", "19\n", "20\n", "21\n", "22\n", "23\n", "24\n", "25\n", "26\n", "27\n", "28\n", "29\n", "30\n", "31\n", "32\n", "33\n", "34\n", "35\n", "36\n", "37\n", "38\n", "39\n", "40\n", "41\n", "42\n", "43\n", "44\n", "45\n", "46\n", "47\n", "48\n", "49\n", "50\n", "51\n", "52\n", "53\n", "54\n", "55\n", "56\n", "57\n", "58\n", "59\n", "60\n", "61\n", "62\n", "63\n", "64\n", "65\n", "66\n", "67\n", "68\n", "69\n", "70\n", "71\n", "72\n", "73\n", "74\n", "75\n", "76\n", "77\n", "78\n", "79\n", "80\n", "81\n", "82\n", "83\n", "84\n", "85\n", "86\n", "87\n", "88\n", "89\n", "90\n", "91\n", "92\n", "93\n", "94\n", "95\n", "96\n", "97\n" ] } ], "source": [ "def setup():\n", " size(500,500)\n", " background('#004477')\n", " no_fill()\n", " stroke('#FFFFFF')\n", " stroke_weight(3)\n", " \n", "def draw():\n", " print(frame_count)\n", "\n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "e2ae5179", "metadata": {}, "source": [ "As long as the above sketch is running, a higher number will be printed to the console for each new frame. You can use `frame_rate()` (with one argument, a number) inside of your setup code to change the FPS at which your sketch runs. \n", "\n", "Using an extra *if* statement and the *modulo* operator (which you may recall gives us the remainder of a division operation), you can easily create a sketch where something only happens every two frames:" ] }, { "cell_type": "code", "execution_count": 11, "id": "9d8bd54d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "4\n", "6\n", "8\n", "10\n" ] } ], "source": [ "def setup():\n", " size(500,500)\n", " background('#004477')\n", " no_fill()\n", " stroke('#FFFFFF')\n", " stroke_weight(3)\n", " frame_rate(2.5) # Slowing our frame rate to make this more visible...\n", " \n", "def draw():\n", " if frame_count % 2 == 0:\n", " print(frame_count)\n", "\n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "babbb82a", "metadata": {}, "source": [ "Let's replace this `print()` function with an ellipse, to draw a circle on even-numbered frames. Actually, the code below may not run as you initially expect." ] }, { "cell_type": "code", "execution_count": 12, "id": "ce92cd04", "metadata": {}, "outputs": [], "source": [ "def setup():\n", " size(500,500)\n", " background('#004477')\n", " no_fill()\n", " stroke('#FFFFFF')\n", " stroke_weight(3)\n", " frame_rate(2.5) # Slowing our frame rate to make this more visible...\n", " \n", "def draw():\n", " if frame_count % 2 == 0:\n", " # print(frame_count)\n", " ellipse(250,140, 47,47)\n", " \n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "d72baabf", "metadata": {}, "source": [ "\n", "\n", "The circle appears, alright, but it doesn't blink on and off. Why? \n", "\n", "Well, py5 draws everything you tell it to, and nothing more. This means that although it's drawing a circle on even-numbered frames, it's not doing anything to remove that circle on odd-numbered frames. To easily solve this problem, you can actually utilize the `background()` function already in your sketch. Simply move it from the `setup()` block to the start of the `draw()` block, and it will be drawn every frame, \"covering up\" whatever happened on the previous frame!" ] }, { "cell_type": "code", "execution_count": 13, "id": "5226b971", "metadata": {}, "outputs": [], "source": [ "def setup():\n", " size(500,500)\n", " no_fill()\n", " stroke('#FFFFFF')\n", " stroke_weight(3)\n", " frame_rate(2.5) # Slowing our frame rate to make this more visible...\n", " \n", "def draw():\n", " background('#004477')\n", " if frame_count % 2 == 0:\n", " # print(frame_count)\n", " ellipse(250,140, 47,47)\n", " \n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "01072dcd", "metadata": {}, "source": [ "Now your ellipse will blink on and off every frame. \n", "\n", "We can of course add an *else* statement to draw another ellipse, in a different position, on odd-numbered frames." ] }, { "cell_type": "code", "execution_count": 14, "id": "a4289d13", "metadata": {}, "outputs": [], "source": [ "def setup():\n", " size(500,500)\n", " no_fill()\n", " stroke('#FFFFFF')\n", " stroke_weight(3)\n", " frame_rate(2.5) # Slowing our frame rate to make this more visible...\n", " \n", "def draw():\n", " background('#004477')\n", " if frame_count % 2 == 0:\n", " # print(frame_count)\n", " ellipse(250,140, 47,47)\n", " else:\n", " ellipse(250,height-140, 47,47)\n", " \n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "c3471559", "metadata": {}, "source": [ "Just like with the animated examples at the top of the page, you can adjust the `frame_rate()` function here to experiment with the results!\n", "\n", "Of course, there are no frames of movement between these two ellipses, making the illusion incomplete. \n", "\n", "\n", "\n", "You could always draw extra ellipses, but this is unnecessarily time-consuming, and we have access to smoother methods of animation. Toggling on and off these two different ellipses is not the best way to accomplish smooth movement - it would be better if we could simply adjust the position of a single ellipse over each frame. In fact, using variables for the position of the ellipse, we can do just that, by adding to and subtracting from those variables. \n", "\n", "## global variables\n", "\n", "When using static sketches, variables can be defined anywhere, and used on any subsequent lines of code. However, our `setup()` and `draw()` blocks have different *scopes*, which means that variables cannot be shared between them. You can see an example of this by trying to run the following code, which defines a variable named *y* inside of `setup()`, then tries to access it in `draw()`." ] }, { "cell_type": "code", "execution_count": 15, "id": "df524f67", "metadata": { "tags": [ "raises-exception", "output_scroll" ] }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "py5 encountered an error in your code:File \"/tmp/ipykernel_93996/2077076397.py\", line 10, in draw\n", " 8 def draw():\n", " 9 background('#004477')\n", "--> 10 print(y)\n", "\n", "NameError: name 'y' is not defined\n" ] } ], "source": [ "def setup():\n", " size(500,500)\n", " no_fill()\n", " stroke('#FFFFFF')\n", " stroke_weight(3)\n", " y = 1\n", "\n", "def draw():\n", " background('#004477')\n", " print(y)\n", " \n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "76aae654", "metadata": {}, "source": [ "This will give some sort of error, for example:\n", "\n", "```\n", "py5 encountered an error in your code:File \"C:\\Users\\PC\\AppData\\Local\\Temp\\ipykernel_6124\\2077076397.py\", line 10, in draw\n", " 8 def draw():\n", " 9 background('#004477')\n", "--> 10 print(y)\n", "\n", "NameError: name 'y' is not defined\n", "```\n", "\n", "When a variable only exists in some limited scope, we call it a *local* variable. To use the same variable throughout your sketch, you will have to define it as a *global* variable instead. The easiest way to do this is simply to move the initial variable declaration - that line like `y = 1` - outside of either the `setup()` or `draw()` blocks. As the following code shows, both blocks can access this global variable." ] }, { "cell_type": "code", "execution_count": 16, "id": "d299f63f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Setup code: 1\n", "Draw code: 1\n", "Draw code: 1\n", "Draw code: 1\n", "Draw code: 1\n", "Draw code: 1\n", "Draw code: 1\n" ] } ], "source": [ "y = 1 # Global variable\n", "\n", "def setup():\n", " size(500,500)\n", " no_fill()\n", " stroke('#FFFFFF')\n", " stroke_weight(3)\n", " frame_rate(2.5)\n", " print( \"Setup code: \" + str(y) ) # prints \"Setup code: 1\" once\n", "\n", "def draw():\n", " background('#004477')\n", " print( \"Draw code: \" + str(y) ) # prints \"Draw code: 1\" once per frame\n", " \n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "383522e1", "metadata": {}, "source": [ "However, trying to reassign this variable in either block will do something funny. You won't actually be editing *y* itself - you'll be overriding it with a *local* version of y." ] }, { "cell_type": "code", "execution_count": 17, "id": "acb742af", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Setup code: 1\n", "Draw code: 0\n", "Draw code: 0\n", "Draw code: 0\n", "Draw code: 0\n", "Draw code: 0\n", "Draw code: 0\n", "Draw code: 0\n", "Draw code: 0\n", "Draw code: 0\n", "Draw code: 0\n" ] } ], "source": [ "y = 1 # Global variable\n", "\n", "def setup():\n", " size(500,500)\n", " no_fill()\n", " stroke('#FFFFFF')\n", " stroke_weight(3)\n", " frame_rate(2.5)\n", " print( \"Setup code: \" + str(y) ) # prints \"Setup code: 1\" once\n", "\n", "def draw():\n", " background('#004477')\n", " y = 0 # Local variable, which overrides y\n", " print( \"Draw code: \" + str(y) ) # prints \"Draw code: 0\" once per frame\n", " \n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "b0dfe429", "metadata": {}, "source": [ "Even worse, trying to edit *y* inside of `draw()` still gives an error, since it's overriding the variable with its own special one." ] }, { "cell_type": "code", "execution_count": 18, "id": "415f650b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Setup code: 1\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "py5 encountered an error in your code:File \"/tmp/ipykernel_93996/1606253102.py\", line 13, in draw\n", " 11 def draw():\n", " 12 background('#004477')\n", "--> 13 y += 1 # Local variable, trying to override y... giving an error\n", " 14 print( \"Draw code: \" + str(y) ) # prints \"Draw code: 0\" once per frame\n", " ..................................................\n", " y = 1\n", " ..................................................\n", "\n", "UnboundLocalError: local variable 'y' referenced before assignment\n" ] } ], "source": [ "y = 1 # Global variable\n", "\n", "def setup():\n", " size(500,500)\n", " no_fill()\n", " stroke('#FFFFFF')\n", " stroke_weight(3)\n", " frame_rate(2.5)\n", " print( \"Setup code: \" + str(y) ) # prints \"Setup code: 1\" once\n", "\n", "def draw():\n", " background('#004477')\n", " y += 1 # Local variable, trying to override y... giving an error\n", " print( \"Draw code: \" + str(y) ) # prints \"Draw code: 0\" once per frame\n", " \n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "bbb88f93", "metadata": {}, "source": [ "That one gives a new error:\n", "\n", "```\n", "UnboundLocalError: local variable 'y' referenced before assignment\n", "```\n", "\n", "So, what's the actual solution? To get things working again, keep that global variable at the top of the code. However, you'll have to add a new line, using the keyword *global*, to tell your `draw()` function to link this *local* reference with the *global* variable.\n", "\n", "While we're here, let's do something useful for animating... and add our `ellipse()` back in, but use *y* to increment its position on the y axis!" ] }, { "cell_type": "code", "execution_count": 19, "id": "35bf8742", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Setup code: 1\n", "Draw code: 2\n", "Draw code: 3\n", "Draw code: 4\n", "Draw code: 5\n", "Draw code: 6\n", "Draw code: 7\n", "Draw code: 8\n", "Draw code: 9\n", "Draw code: 10\n", "Draw code: 11\n", "Draw code: 12\n", "Draw code: 13\n", "Draw code: 14\n", "Draw code: 15\n", "Draw code: 16\n", "Draw code: 17\n", "Draw code: 18\n", "Draw code: 19\n", "Draw code: 20\n", "Draw code: 21\n", "Draw code: 22\n", "Draw code: 23\n", "Draw code: 24\n", "Draw code: 25\n", "Draw code: 26\n", "Draw code: 27\n", "Draw code: 28\n", "Draw code: 29\n", "Draw code: 30\n", "Draw code: 31\n", "Draw code: 32\n", "Draw code: 33\n", "Draw code: 34\n", "Draw code: 35\n", "Draw code: 36\n", "Draw code: 37\n", "Draw code: 38\n", "Draw code: 39\n", "Draw code: 40\n", "Draw code: 41\n", "Draw code: 42\n", "Draw code: 43\n", "Draw code: 44\n", "Draw code: 45\n", "Draw code: 46\n", "Draw code: 47\n", "Draw code: 48\n", "Draw code: 49\n", "Draw code: 50\n", "Draw code: 51\n", "Draw code: 52\n", "Draw code: 53\n", "Draw code: 54\n", "Draw code: 55\n", "Draw code: 56\n", "Draw code: 57\n", "Draw code: 58\n", "Draw code: 59\n", "Draw code: 60\n", "Draw code: 61\n", "Draw code: 62\n" ] } ], "source": [ "y = 1 # Global variable\n", "\n", "def setup():\n", " size(500,500)\n", " no_fill()\n", " stroke('#FFFFFF')\n", " stroke_weight(3)\n", " frame_rate(30) # Trust me, leaving this at 2.5 will be too slow\n", " print( \"Setup code: \" + str(y) ) # prints \"Setup code: 1\" once\n", "\n", "def draw():\n", " global y # Bringing the global variable, y, into this scope\n", " background('#004477')\n", " y += 1 # Adding to y each frame\n", " print( \"Draw code: \" + str(y) ) # prints \"Draw code: \" and current y value once per frame\n", " ellipse(height/2,y, 47,47) # Draws our ellipse at y each frame!\n", " \n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "fca1c7c0", "metadata": {}, "source": [ "Run this code. You'll be able to watch the ellipse slide down the screen. \n", "\n", "## saving frames as images\n", "\n", "py5 has a few different ways to produce image files from your sketch, like `save()` and `save_frame()`. We'll be looking at `save_frame()` here, since we've just started working with animation.\n", "\n", "By adding these two lines to your code, you can \"take a picture\" every 100 frames. (You wouldn't want to use this with a very slow frame rate, as you'd be waiting a long time!) The argument that I've given it is the filename, including the file extension, that will determine how the file is saved.\n", "\n", "```\n", "if frame_count % 100 == 0:\n", " save_frame('file.png')\n", "```" ] }, { "cell_type": "code", "execution_count": 20, "id": "9df3de5d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Setup code: 1\n", "Draw code: 2\n", "Draw code: 3\n", "Draw code: 4\n", "Draw code: 5\n", "Draw code: 6\n", "Draw code: 7\n", "Draw code: 8\n", "Draw code: 9\n", "Draw code: 10\n", "Draw code: 11\n", "Draw code: 12\n", "Draw code: 13\n", "Draw code: 14\n", "Draw code: 15\n", "Draw code: 16\n", "Draw code: 17\n", "Draw code: 18\n", "Draw code: 19\n", "Draw code: 20\n", "Draw code: 21\n", "Draw code: 22\n", "Draw code: 23\n", "Draw code: 24\n", "Draw code: 25\n", "Draw code: 26\n", "Draw code: 27\n", "Draw code: 28\n", "Draw code: 29\n", "Draw code: 30\n", "Draw code: 31\n", "Draw code: 32\n", "Draw code: 33\n", "Draw code: 34\n", "Draw code: 35\n", "Draw code: 36\n", "Draw code: 37\n", "Draw code: 38\n", "Draw code: 39\n", "Draw code: 40\n", "Draw code: 41\n", "Draw code: 42\n", "Draw code: 43\n", "Draw code: 44\n", "Draw code: 45\n", "Draw code: 46\n", "Draw code: 47\n", "Draw code: 48\n", "Draw code: 49\n", "Draw code: 50\n" ] } ], "source": [ "y = 1 # Global variable\n", "\n", "def setup():\n", " size(500,500)\n", " no_fill()\n", " stroke('#FFFFFF')\n", " stroke_weight(3)\n", " frame_rate(30) # Trust me, leaving this at 2.5 will be too slow\n", " print( \"Setup code: \" + str(y) ) # prints \"Setup code: 1\" once\n", "\n", "def draw():\n", " global y # Bringing the global variable, y, into this scope\n", " background('#004477')\n", " y += 1 # Adding to y each frame\n", " print( \"Draw code: \" + str(y) ) # prints \"Draw code: \" and current y value once per frame\n", " ellipse(height/2,y, 47,47) # Draws our ellipse at y each frame!\n", " \n", " if frame_count % 100 == 0:\n", " save_frame('file.png')\n", " \n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "9cbd4604", "metadata": {}, "source": [ "If you're running this code online, the resulting file may be quite hard to find. However, in any development environment hosted on your computer, `file.png` will be placed in the same folder as the sketch, and updated every 100 frames. \n", "\n", "## DVD screensaver task\n", "\n", "It's time for a challenge, putting your new knowledge about frames and animation to use.\n", "\n", "What exactly is a DVD screensaver? Well, DVD players (if you remember those) often have a screensaver where their logo slides around on the screen, bouncing back when it hits a wall or corner. (Have you ever found yourself waiting around for that logo to perfectly hit the corner? You're not alone... and there's an excellent post on [The Lost Math Lessons](http://lostmathlessons.blogspot.com/2016/03/bouncing-dvd-logo.html) calculating how long this might take.) \n", "\n", "Instead of making you draw your own, we'll be using a generic DVD logo here. You can save it into the same folder as your sketch on your computer, or directly reference it by its complete URL.\n", "\n", "\n", "\n", "Here's some code to get you started. Most of it will be at least a little familiar." ] }, { "cell_type": "code", "execution_count": 21, "id": "b6979a0d", "metadata": {}, "outputs": [], "source": [ "x = 0\n", "xspeed = 2\n", "logo = None\n", "\n", "def setup():\n", " global logo\n", " size(800,600)\n", " logo = load_image('images/animation_and_motion/dvd-logo.png')\n", "\n", "def draw():\n", " global x, xspeed, logo\n", " background('#000000')\n", " x += xspeed\n", " image(logo, x,100)\n", "\n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "017a093f", "metadata": {}, "source": [ "You can see we're following the same general format as before: global variables are declared at the top of the sketch, and the *global* keyword is used whenever they must be changed. Notice that loading an image with `load_image()` is done inside of our `setup()` block, overwriting the placeholder \"None\". Since `load_image()` is a function, we run it just once on startup by doing this. \n", "\n", "In addition to x, we also use a variable, *xspeed*, so that we can easily adjust the speed at which our logo moves. Right now, the logo will slide all the way to the right and off the right side of the screen.\n", "\n", "So how do we make sure it *bounces back*? You might remember that the maximum width of the window is stored in a built-in variable named *width*. We can use this to check if *x* (and thus the position of the logo) has moved to the edge of the screen. This will fill the console with `Bye!` once the DVD logo disappears:" ] }, { "cell_type": "code", "execution_count": 22, "id": "37d8b6f4", "metadata": {}, "outputs": [], "source": [ "x = 0\n", "xspeed = 2\n", "logo = None\n", "\n", "def setup():\n", " global logo\n", " size(800,600)\n", " logo = load_image('images/animation_and_motion/dvd-logo.png')\n", "\n", "def draw():\n", " global x, xspeed, logo\n", " background('#000000')\n", " x += xspeed\n", " image(logo, x,100)\n", " if (x >= width):\n", " print('Bye!')\n", "\n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "8c95a2b9", "metadata": {}, "source": [ "Since the movement of the logo is controlled by xspeed, we can reverse its motion by changing xspeed into a negative number. Try this to bounce the logo off the right side of the screen:" ] }, { "cell_type": "code", "execution_count": 23, "id": "5523f848", "metadata": {}, "outputs": [], "source": [ "x = 0\n", "xspeed = 2\n", "logo = None\n", "\n", "def setup():\n", " global logo\n", " size(800,600)\n", " logo = load_image('images/animation_and_motion/dvd-logo.png')\n", "\n", "def draw():\n", " global x, xspeed, logo\n", " background('#000000')\n", " x += xspeed\n", " image(logo, x,100)\n", " if (x >= width):\n", " # print('Bye!')\n", " xspeed *= -1 # Multiplying xspeed by negative 1\n", "\n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "86c310b1", "metadata": {}, "source": [ "This bounce isn't perfect... the logo almost completely disappears before it bounces back, because its anchor point is at the top-left corner of the image. We can compensate for this by subtracting the width of the image from our calculations. (As a hint, this logo is 100 pixels wide and 45 pixels tall.)" ] }, { "cell_type": "code", "execution_count": 24, "id": "db74e04e", "metadata": {}, "outputs": [], "source": [ "x = 0\n", "xspeed = 2\n", "logo = None\n", "\n", "def setup():\n", " global logo\n", " size(800,600)\n", " logo = load_image('images/animation_and_motion/dvd-logo.png')\n", "\n", "def draw():\n", " global x, xspeed, logo\n", " background('#000000')\n", " x += xspeed\n", " image(logo, x,100)\n", " if (x >= (width - 100)):\n", " # print('Bye!')\n", " xspeed *= -1 # Multiplying xspeed by negative 1\n", "\n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "e51fe442", "metadata": {}, "source": [ "What about the left side of the screen? Well, that's as simple as adding another check for an x position of less than zero. We don't even have to do any math with the width of the logo here, since it's anchored on the top-left corner by default. Since the same thing has to happen on either end of the screen (reversing the xspeed variable), you can use the *or* operator to combine this check with the last one." ] }, { "cell_type": "code", "execution_count": 1, "id": "5824d981", "metadata": {}, "outputs": [], "source": [ "x = 0\n", "xspeed = 2\n", "logo = None\n", "\n", "def setup():\n", " global logo\n", " size(800,600)\n", " logo = load_image('images/animation_and_motion/dvd-logo.png')\n", "\n", "def draw():\n", " global x, xspeed, logo\n", " background('#000000')\n", " x += xspeed\n", " image(logo, x,100)\n", " if (x >= (width - 100) or x <= 0):\n", " # print('Bye!')\n", " xspeed *= -1 # Multiplying xspeed by negative 1\n", "\n", "run_sketch()" ] }, { "cell_type": "markdown", "id": "726aabac", "metadata": {}, "source": [ "\n", "\n", "Now the DVD logo will bounce back and forth every time it hits a wall.\n", "\n", "The missing component here is the possibility for the logo to bounce up and down, too. You'll need to add variables for *y* and *yspeed*, and make them global where appropriate, as well as work on detecting when the logo hits the top and bottom of the screen.\n", "\n", "Blazing through it? Here's another challenge - using the `random()` function, make the value of xspeed and yspeed (and thus the starting angle) randomize every time the sketch is run!" ] } ], "metadata": { "jupytext": { "formats": "ipynb,md:myst" }, "kernelspec": { "display_name": "py5", "language": "python", "name": "py5" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.5" } }, "nbformat": 4, "nbformat_minor": 5 }