Mouse Interaction (Video Version)
-
0:01 - 0:04You've already learned how to make your own variables and use them.
-
0:04 - 0:14Now we're gonna learn about two special variables: mouseX and mouseY
-
0:14 - 0:17Now you never have to make these variables yourself, and in fact you shouldn't,
-
0:17 - 0:27because they already exist. Some awesome person already did the whole "var mouseX" and "var mouseY" thing so you don't have to,
-
0:27 - 0:32and the same awesome person made it so that the value of mouseX is always the x-position of your mouse,
-
0:32 - 0:36and the value of mouseY is always the y-position of your mouse.
-
0:36 - 0:40This makes it really easy to do cool interactive things, like this:
-
0:40 - 0:44Check out this ellipse I'm drawing. Right now I'm always drawing it at 200, 200
-
0:44 - 0:51Instead, I can use these special variables and draw it at mouseX and mouseY
-
0:51 - 0:56And now, if I move my mouse over the canvas, you can see the ellipse is always being drawn where my mouse is,
-
0:56 - 1:00so it follows my mouse around! So that's pretty cool.
-
1:00 - 1:04If you're gonna use mouseX and mouseY you've got to make sure that you use them inside this draw loop,
-
1:04 - 1:08because look what happens if we move these two lines of code outside the draw loop.
-
1:08 - 1:15Now, they're only gonna get run once, and this ellipse will only be drawn where my mouse was at the very beginning of the program.
-
1:15 - 1:23So that's why we need the draw loop. Because, if you think about it, even though it may not feel like it, this is also a kind of animation
-
1:23 - 1:29Now we can do all sorts of fun things. So what if, instead of drawing it at mouseX and mouseY I drew it at mouseX,
-
1:29 - 1:37and then fixed mouseY at something like 300, and now the ellipse only follows my x-coordinate,
-
1:37 - 1:40the x-coordinate of my mouse, but not the y.
-
1:40 - 1:48Yeah? And then maybe I can draw it at mouseX and mouseY again but then get rid of this background() line.
-
1:48 - 1:55So now we're gonna see all of the ellipses that we drew before, so we've got this funky paintbrush kind of thing.
-
1:55 - 2:05That's pretty awesome. Or, I could even switch these variables, so draw it at mouseY and mouseX, and now it's kind of like before
-
2:05 - 2:10except the mouse controls are all messed up, but that's cool too, you can imagine making a whole game about trying to draw something
-
2:10 - 2:13trying to write something with these messed-up controls.
-
2:13 - 2:17So that's it for mouseX and mouseY! Super easy to use, but super awesome.
- Title:
- Mouse Interaction (Video Version)
- Description:
-
This is just a screen grab of our interactive coding talk-through, prepared to make captioning and translation easier. It is better to watch our talk-throughs here:
https://www.khanacademy.org/cs/programming/ - Video Language:
- English
- Duration:
- 02:19
kramtark edited English subtitles for Mouse Interaction (Video Version) |