HTML and CSS Reference
In-Depth Information
rotation and position of the base determine the position of segment1 . And segment1 's rotation and
position determine the position of the free end. The free end has no say in where it is, should be, or would
like to be—it just goes along for the ride. Thus, control moves forward from the base to the free end.
Automating the Process
All these sliders for rotation give you a lot of control, but what you've created is something like a piece of
construction machinery with hydraulic levers to move around the parts. If you want to make something
really walk, step back and give it some self-control.
You need a way for each segment to smoothly swing back and forth, and then somehow synchronize them
all. That sounds like a job for a sine wave.
In example 05-walking-1.html , we replaced the sliders with a trigonometry function. It takes the sine of
the cycle variable (which is initialized to 0) and multiplies it by 90, resulting in a value from 90 to -90. The
cycle variable is constantly increased, so you get an oscillation. For now, we used the resulting angle
variable to control both segments. The drawFrame function has been converted to an animation loop that
controls the action, so the motion is continuous. The output looks like the previous example, except this
time the motion is automated.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Walking 1</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="segment.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
segment0 = new Segment(100, 20),
segment1 = new Segment(100, 20),
cycle = 0;
segment0.x = 200;
segment0.y = 200;
segment1.x = segment0.getPin().x;
segment1.y = segment0.getPin().y;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
cycle += 0.02;
 
Search WWH ::




Custom Search