Here's the Code
We'll cover the following...
The full code for making this example work looks as follows:
Just like all of our previous examples, our code assumes that you have a canvas element with an id value of myCanvas defined in your HTML. The rest is handled by the lines of JavaScript that you see.
In the following sections, we are going to be taking parts of this code and looking at in greater detail. Before we do that, to make the most of our time together, you should take a few minutes and walk through the code by yourself and try to see how what you see maps to the mouse follow example you saw a few moments earlier. Once you have given the code a good glance through, we’ll look at the interesting parts together…starting…now!
How the Easing (Deceleration) Works
The first thing we are going to look at is how the square decelerates its way towards the mouse cursor. The way we accomplish this is by forcing our square to take incremental steps towards where the mouse cursor is. That probably makes no sense, so let’s walk through what I mean by that.
At the very beginning, you have a situation that looks as follows:
Your mouse cursor is somewhere. Your square is somewhere else. The goal is for our square to get to where the mouse cursor is:
Looking at where the square needs to go in the form a straight line makes sense for us, but we have to break that down ...