-
You've already learned how
to make your own variables and use them.
-
Now we're going to learn
about two special variables:
-
mouseX and mouseY.
-
You never have to make
these variables yourself,
-
and in fact you shouldn't,
because they already exist.
-
You see, the program sets the values
of these variables behind the scenes,
-
making sure that the value of mouseX
is always the x position of your mouse,
-
and the value of mouseY
is always the y position of your mouse.
-
This makes it really easy to do
cool, interactive things
-
based on the user's mouse position.
-
Let's look at this ellipse
that I'm drawing here.
-
So, right now,
I'm always drawing it at 200, 200.
-
If I use mouseX and mouseY,
these special variables,
-
then I can actually draw it
at mouseX and mouseY.
-
Now, if I move my mouse
over the canvas, you can see
-
the ellipse is always being drawn
where my mouse is --
-
so it follows my mouse around.
-
That's pretty cool; can you tell
what I'm drawing? Whee!
-
If you're going to use mouseX and mouseY,
you've got to make sure
-
that you use them inside
the draw = function ()
-
because look what happens
-
if we move these two lines of code
outside the draw = function ().
-
You see?
-
Now this code here only gets run once,
-
so this ellipse is only drawn once,
-
and it's drawn wherever my mouse
happened to be
-
at the very, very beginning
of the program.
-
That's why we need to have it
inside the draw = function (),
-
because the draw = function ()
is this function
-
that's called repeatedly over
and over while our program is running.
-
So we want that when it gets called,
it looks at what the current value
-
of mouseX and mouseY is, and then
it draws the ellipse at that position.
-
If you think about it, it's
actually very similar to an animation --
-
it's changing over time,
just in a different way.
-
Okay, now we can do
all sorts of fun things.
-
What if, instead of drawing it
at mouseX and mouseY,
-
I drew it at mouseX still but I fixed
mouseY at something like 300?
-
Now you can see that the ellipse
only follows my x coordinate,
-
ignoring whatever I do in the y.
-
Then, what if I now draw it at mouseX
and mouseY, bringing that back,
-
but I get rid of the background,
just commenting that out?
-
Woo! Now look, I've got
this funky paintbrush thing.
-
That's pretty awesome.
-
Or, or, I could even switch
these variables.
-
Let me bring back our background.
-
I'll switch these variables here,
mouseY and mouseX,
-
and then see what happens.
-
Now it just feels really, really weird.
-
I've got these mouse controls
that are doing opposite
-
of what I would expect them to.
-
But that's cool, you could imagine
making a whole game
-
which is about trying to draw something
or do something
-
while using inverted mouse controls.
-
That's it for mouseX and mouseY --
really, pretty fun. Enjoy!