HTML and CSS Reference
In-Depth Information
vx += ax;
vy += ay;
vx *= friction;
vy *= friction;
ship.x += vx;
ship.y += vy;
//screen wrapping
if (ship.x - ship.width / 2 > right) {
ship.x = left - ship.width / 2;
} else if (ship.x + ship.width / 2 < left) {
ship.x = right + ship.width / 2;
}
if (ship.y - ship.height / 2 > bottom) {
ship.y = top - ship.height / 2;
} else if (ship.y < top - ship.height / 2) {
ship.y = bottom + ship.height / 2;
}
ship.draw(context);
}());
That's a different feel for just three new lines of code.
Don't forget to think outside the x, y box. Friction can be applied anywhere you have any type of velocity.
Maybe you have something that rotates (with a vr property), applying friction to that eventually causes it to
slow down and stop spinning. You can try that with the spinning arrow example from Chapter 5.
You can see how you can use this approach for all types of objects, such as a roulette wheel, an electric fan, or a propeller.
Important formulas in this chapter
Let's review the important formulas introduced in this chapter.
Remove an out-of-bounds object
if (object.x - object.width / 2 > right ||
object.x + object.width / 2 < left ||
object.y - object.height / 2 > bottom ||
object.y + object.height / 2 < top) {
//code to remove object
}
Regenerate an out-of-bounds object
if (object.x - object.width / 2 > right ||
object.x + object.width / 2 < left ||
object.y - object.height / 2 > bottom ||
object.y + object.height / 2 < top) {
//reset object position and velocity
}
 
Search WWH ::




Custom Search