HTML and CSS Reference
In-Depth Information
Get the distance from segment1 to the mouse.
Get the lengths of the three sides. Sides a and b are easy. They're equal to 100, because
that's how long we made the segments. Side c is equal to dist or a + b , whichever is
smaller. This is because one side of a triangle can't be longer than the other two sides
added together.
Figure out angles B and C using the law of cosines formula, and angle D using
Math.atan2 . angle E , as mentioned, is D + B + 180 + C . But in code, you substitute
Math.PI radians for 180 degrees.
Just as the diagram in Figure 14-8 shows, use the angle D + B as segment1 's rotation. Use
the same angle to find the end point of segment1 and position segment0 on it.
Finally, segment0 's rotation is angle E .
So that's inverse kinematics using the law of cosines. You might notice that the joint always bends
the same way. This might be good if you're building something like an elbow or a knee that can
bend only one way, but what if you want to bend it the other way?
When you figure out the angles analytically like this, there are two solutions to the problem: It can
bend this way, or it can bend that way. You coded it to bend one way by adding D and B , and then
adding C . If you subtracted them all, you get the same effect, but the segment bends in the other
direction. Here's the modified drawFrame function to see how this looks (document 09-cosines-
2.html ):
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var dx = mouse.x - segment1.x,
dy = mouse.y - segment1.y,
dist = Math.sqrt(dx * dx + dy * dy),
a = 100,
b = 100,
c = Math.min(dist, a + b),
B = Math.acos((b * b - a * a - c * c) / (-2 * a * c)),
C = Math.acos((c * c - a * a - b * b) / (-2 * a * b)),
D = Math.atan2(dy, dx),
E = D - B + Math.PI - C;
segment1.rotation = (D - B);
var target = segment1.getPin();
segment0.x = target.x;
segment0.y = target.y;
segment0.rotation = E;
segment0.draw(context);
segment1.draw(context);
}());
Search WWH ::




Custom Search