HTML and CSS Reference
In-Depth Information
var x1 = ball.x - centerX,
y1 = ball.y - centerY,
x2 = x1 * cos - y1 * sin,
y2 = y1 * cos + x1 * sin;
ball.x = centerX + x2;
ball.y = centerY + y2;
ball.draw(context);
}());
};
</script>
</body>
</html>
Here, you are setting vr to the same value of 0.05 you used before. Then you're calculating the sine and
cosine of that angle. Since those values won't change during this simple example, you can calculate it
once at the top of the script, rather than recalculating it every frame. The x1 and y1 positions are
calculated in relation to the point they will rotate around—the center of the canvas. Then you apply the
coordinate rotation formula as just described. This gives you x2 and y2 , the new position of the ball. Again,
this is in relation to the center point, so you need to add x2 and y2 to the center point to get the final
position of the ball.
Try it out, and you'll see it should work exactly the same as the earlier version. Now, why bother going
through this new, more complex, formula when the results look the same? Well, in a simple situation like
this, you might not. But let's look at some examples where this setup actually simplifies things. First,
consider rotating multiple objects.
Rotating multiple objects
Suppose there are many objects to rotate, say a bunch of objects in an array called balls . Moving each
ball would look something like this:
balls.forEach(function (ball) {
var dx = ball.x - centerX,
dy = ball.y - centerY,
angle = Math.atan2(dy, dx),
dist = Math.sqrt(dx * dx + dy * dy);
angle += vr;
ball.x = centerX + Math.cos(angle) * dist;
ball.y = centerY + Math.sin(angle) * dist;
});
Whereas the advanced coordinate rotation method would look like this:
var cos = Math.cos(vr),
sin = Math.sin(vr);
balls.forEach(function (ball) {
var x1 = ball.x - centerX,
y1 = ball.y - centerY,
 
Search WWH ::




Custom Search