HTML and CSS Reference
In-Depth Information
segment0.draw(context);
}());
The segment is now permanently attached to the mouse and rotates to drag along behind it. You can even
push the segment around in the opposite direction.
Dragging Multiple Segments
Dragging a system with inverse kinematics is a bit simpler than reaching, so we cover that first. We begin
moving a couple of segments.
Dragging Two Segments
Starting with the previous example, create another segment, segment1 , at the top of the script. Because
segment0 is already dragging to the mouse position, you have segment1 drag on segment0 . To start with,
you can use some of the same code as before—just change a few references. The new additions to the
drawFrame function are shown in bold:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var dx = mouse.x - segment0.x,
dy = mouse.y - segment0.y;
segment0.rotation = Math.atan2(dy, dx);
var w = segment0.getPin().x - segment0.x,
h = segment0.getPin().y - segment0.y:
segment0.x = mouse.x - h;
segment0.y = mouse.y - w;
dx = segment0.x - segment1.x;
dy = segment0.y - segment1.y;
segment1.rotation = Math.atan2(dy, dx);
w = segment1.getPin().x - segment1.x;
h = segment1.getPin().y - segment1.y;
segment1.x = segment0.x - w;
segment1.y = segment0.y - h;
segment0.draw(context);
segment1.draw(context);
}());
In the new section of code, you figure out the distance from segment1 to segment0 , and use that for the
angle, rotation, and position of segment1 —reusing the variables from the previous calculation. You can
test this example and see how it's a pretty realistic two-segment system.
 
Search WWH ::




Custom Search