This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

User Interaction in WebGL

3:10 JavaScript lesson by

In this lesson we accomplish some simple user interaction with animated 3D vertices.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

In this lesson we accomplish some simple user interaction with animated 3D vertices.

We'll start here with the code we created in lesson "Animating Vertices." This creates 5,000 vertices and animates them by changing their position slightly within each frame. Let's add a bit of interaction to it. I'll add a mouseX and mouseY variable up at the top here, and set them both to 0. Then I'll add an event listener to canvas listening for the mouseMove event. Now remember that our vertices are in a coordinate system that goes from -1 to +1 on both axes, while the canvas goes from 0 to 600 on each axis.

So we need to convert our mouse position to the webgl coordinates. I'm going to paste a function in here called map. This takes a value plus a source and destination range, and maps that value from the source range to the destination range. Then I'll say mouseX = map(event, clientX, 0, canvas.width -1, 1) source range is the0 to canvas width, and the destination range is -1 to +1 of the webgl x-axis. For mouseY I'll say map(event, clientY, 0, canvas.height,1,-1).

Note that I reversed the signs in the destination range, so that 0 of the canvas Y, the top of the canvas, maps to 1 in the webgl coordinates. Now down in the draw function as we loop through each vertex, I'm going to find its distance to mouseX and mouseY. I'll do that by finding the distance on the x-axis, and then on the y-axis, squaring those, and adding them, and taking the square root, the Pythagorean theorem. Then if the distance is less than a certain amount, say 0.2, I'll do something special, else, I'll do the random shake that we've been doing.

Now the special thing I want to do here is move the X and Y of the affected vertices out away from the mouse a certain distance, again, that 0.2. To do that I'll reset vertices i and vertices i +1, the x and y coordinates. I'm going to make x, mouseX + dx * distance * 0.2, and y, mouseY + dy / distance * 0.2. This is just a tricky shortcut for some more complex trigonometry, not really important for the purpose of this lesson. That's it, let's test it.

Now when we move the mouse, any vertices within that 0.2 distance from the mouse get pushed out away from the mouse. Vertices further away continue to shake around just like before, so it's like you're pushing around grains of sand with an invisible finger, pretty neat effect. There's lots of places you could take this very simple example. I'm just messing around with the point size and color. Try some other changes and see what they do.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?