HTML and CSS Reference
In-Depth Information
Screen wrapping for an out-of-bounds object
if (object.x - object.width / 2 > right) {
object.x = left - object.width / 2;
} else if (object.x + object.width / 2 < left) {
object.x = right + object.width / 2;
} if (object.y - object.height / 2 > bottom) {
object.y = top - object.height / 2;
} else if (object.y + object.height / 2 < top) {
object.y = bottom + object.height / 2;
}
Apply friction (the correct way)
speed = Math.sqrt(vx * vx + vy * vy);
angle = Math.atan2(vy, vx);
if (speed > friction) {
speed -= friction;
} else {
speed = 0;
}
vx = Math.cos(angle) * speed;
vy = Math.sin(angle) * speed;
Apply friction (the easy way)
vx *= friction;
vy *= friction;
Summary
This chapter covered an object's interaction with its environment—specifically, an object's interaction with
the edges of its universe and the universe itself. You learned the possible ways to handle an object that
has gone off the edge of the world, including removing, regenerating, wrapping, and bouncing. And, you
now know all about applying friction to objects. With these simple techniques, you can make the objects in
your animations move with a great deal of realism. In the next chapter, you allow the user to interact with
the objects.
 
Search WWH ::




Custom Search