HTML and CSS Reference
In-Depth Information
}
var speed = 6;
var gravity = .1;
var elasticity = .5;
var angle = 285;
var radians = angle * Math.PI/ 180;
var radius = 15;
var vx = Math.cos(radians) * speed;
var vy = Math.sin(radians) * speed;
theCanvas = document.getElementById("canvasOne");
context = theCanvas.getContext("2d");
var p1 = {x:20,y:theCanvas.width-radius};
var ball = {x:p1.x, y:p1.y, velocityx: vx, velocityy:vy, radius:radius,
elasticity: elasticity};
setInterval(drawScreen, 33);
}
</script>
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="500" height="500">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
</body>
</html>
Simple Gravity, Simple Elasticity, and Simple Friction
Now that we have a ball traveling on a vector that is affected by both gravity and
elasticity, we have one more element to add to make the animation more realistic. In
the previous example, the y velocity was affected by gravity and elasticity, but the ball
still traveled on the x-axis without any degradation in velocity. We will fix this issue
now by adding friction into the equation.
In physics, friction is a force that resists the motion of an object. We have already
discussed friction as it applies to colliding balls, and this implementation is similar
except that it affects only the x velocity. For our purposes, we will achieve simple friction
by degrading the x velocity as gravity degrades the y velocity.
Taking the code from Example 5-16 , in canvasApp() we create a new variable named
friction . This is the amount of pixels to degrade the x velocity on every frame:
var friction = .008;
Search WWH ::




Custom Search