It's
simple enough in concept, but the code is a
bit of a mouthful.
These lines really just do some fairly boring arithmetic to calculate the edges of things, allowing for the margin, and change the viewport by the appropriate amount.
If you want, pick one of those lines and work through to understand how and why it achieves our goal.
But the English equivalent is "if the hero goes too near the edge, move the viewport".
var viewport_margin = 10; // how close the hero can get to the edge before we scroll
function handle_keys_that_are_pressed() {
var prev_x = hero.x;
var prev_y = hero.y;
if (keys[37]) { // Left
hero.x -= hero_speed;
if (hero.x < viewport_margin-viewport_offset_x)
viewport_offset_x += (viewport_margin - viewport_offset_x - hero.x);
}
if (keys[39]) { // Right
hero.x += hero_speed;
if (hero.x + hero.w > myCanvas.width - viewport_margin - viewport_offset_x)
viewport_offset_x += (myCanvas.width - viewport_margin - viewport_offset_x - hero.x - hero.w);
}
if (keys[38]) { // Up
hero.y -= hero_speed;
if (hero.y < viewport_margin-viewport_offset_y)
viewport_offset_y += (viewport_margin - viewport_offset_y - hero.y);
}
if (keys[40]) { // Down
hero.y += hero_speed;
if (hero.y + hero.h > myCanvas.height - viewport_margin - viewport_offset_y)
viewport_offset_y += (myCanvas.height - viewport_margin - viewport_offset_y - hero.y - hero.h);
}
if (is_touching_an_obstacle(hero)) {
hero.x = prev_x; // moved into an obstacle so undo the move
hero.y = prev_y;
}
if (hero.x == prev_x && hero.y == prev_y) hero.animation_rate= 0 // not moving
else hero.animation_rate= 2; // wriggling legs
}