Hello my friends, in this new entry I am going to show you how to make cool animations with some algebra and Python, algebra? Yes my friend, because animating an object is based on some transformation of coordinates, translating or rotating for example, but we will get into that don't worry; Now let's talk about the Python Tools that we are going to use.
With numpy we can make and manipulate arrays with Python, the array type in this package has methods that can use for common operations in algebra, among other uses with also are going to take into account the trigonometric functions, sin and cos, useful for rotations.
With matplotlib we can create pretty cool plots, and turning the interactive mode on, we can make some iteractive plots hence a cool animation. Let me show you the final result for our code so you can have a pretty good idea.
Cool right, as we can see on the animation, a small pacman figure is moving through a small maze, and in each corner it will turn or rotate to keep moving through the maze or blue path. The code for this is very simple, so let's do the next thing, I will show you the entire code and explain the parts that could be tricky.
As always we make the importation of the packages (our tools) that we are going to use, in this case numpy and matplotlib.
Then we are going to create some functions, 2 of those are anonymous functions, if you are not familiar with these kind of functions you can check my entry of lambda, these functions can take some arguments and will return a matrix or double size array, based on these matrix, by making dot product with some coordinates in array shape, you can rotate or translate those coordinates, in this way how we can make animations.
The main two steps in the animations are,
· Create new coordinates, by translating or rotating
· Update interactively the plot with new coordinates
These two steps are made in a function call animate, that takes the global variables with the coordinates of the maze and the packman figure and update the plot, in this functions there are also some conditional statements to check whether the pacman figure has reached a corner in order to rotate it.
Something else to point out is for us to be able to update the plot we need to turn the interactive mode of matplotlib on, we can do this by using plt.ion(), and that is all.
Finally we use a for loop for making the frame update with a pause to control the speed of refreshing the plot, and a conditional statement to break the for loop if the pacman figure has reached the end.
Well my friend we have come to the end of this entry, hope you can use some of this code in your programing.
So thanks for coming by my new entry and I hope you have enjoyed this as much as I enjoyed writing it, stop by the comments if you want to discuss about this, share in your social media and subscribe. Cheers my friends.