A Quick Refactoring
Although it was perfectly adequate for what we were trying to achieve, the rot method in the previous post in fact bundled two responsibilities: one was the actual rotation, based on mouse position, and the other was to update the matrix based on the current rotation.
In order to incorporate the new event, we need to split those responsibilities. So let's create a new update function at the top level and call that from within our rot function.
function update(comp) {
var m = comp.matrix;
m.id();
m.$rotateXYZ(comp.rotation.x, comp.rotation.y, comp.rotation.z);
m.$translate(comp.position.x, comp.position.y, comp.position.z);
m.$scale(comp.scale.x, comp.scale.y, comp.scale.z);
}
The Event Handler
The next step is to track the scroll events and remember how far in or out of the screen the cones currently are. We can do this by adding an event handler for onMouseWheel in the same way that the moon example did, and then tracking the current depth and updating both cones.At the outermost scope within the loadConics() function, we can declare a current depth, i.e. how far the cones are in or out. Note that it is very important to initialize this variable because otherwise the mathematics that depends upon it will fail and nothing will render.
var depth = 0;And then in the events section, we can add the handler that updates it:
onMouseWheel: function(e) {Finally, we need to use this value in our update method. Going back to what we said about order of operations in the last post, it's very important that this translation is the last thing that is done. How do we manage that while at the same time insisting that the y translation is done before the rotation? Well, quite simply, we are allowed to call translate (and indeed any of the operations) multiple times. We invoke translate twice, once for the y translation and once for the z translation. Of course, these are still written "backwards", so we end up with this:
e.stop();
depth -= e.wheel;
update(top);
update(bottom);
}
function update(comp) {Now we can move the cones in and out of the screen. This is tagged MOVE_CONES_BACKWARDS_FORWARDS.
var m = comp.matrix;
m.id();
m.$translate(0, 0, depth);
m.$rotateXYZ(comp.rotation.x, comp.rotation.y, comp.rotation.z);
m.$translate(comp.position.x, comp.position.y, comp.position.z);
m.$scale(comp.scale.x, comp.scale.y, comp.scale.z);
}
No comments:
Post a Comment