HTML and CSS Reference
In-Depth Information
vx = Math.cos(45 * Math.PI / 180) * 1;
vy = Math.sin(45 * Math.PI / 180) * 1;
These functions each return a value of approximately 0.707. After you have the vx and the vy , you can
easily add these to the x, y position of the object you are animating.
The next example (03-velocity-angle.html) has the following code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Velocity Angle</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
ball = new Ball(),
angle = 45,
speed = 1;
ball.x = 50;
ball.y = 100;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var radians = angle * Math.PI / 180,
vx = Math.cos(radians) * speed,
vy = Math.sin(radians) * speed;
ball.x += vx;
ball.y += vy;
ball.draw(context);
}());
};
</script>
</body>
</html>
The main difference here is that you start off with angle and speed rather than vx and vy . The velocities
are calculated as local variables, used, and discarded. Of course, in a simple case like this, where the
angle and speed are never changing, it makes more sense to calculate the velocities once and save them
as variables at the top of the script. But in most advanced motions, both the direction and speed of motion
will constantly change, so the vx and vy will not remain the same.
Search WWH ::




Custom Search