Recall our
Do_Frame_Things method of MySprite included a couple of lines of
code to change the position by the velocity:
MySprite.prototype.Do_Frame_Things = function() {
this.x = this.x + this.velocity_x;
this.y = this.y + this.velocity_y;
if (this.visible) ctx.drawImage(this.MyImg, this.x, this.y); // draw the thing
}
We need to alter it to only change the position if the sprite isn't already starting to go off-screen.
It's slightly more complicated than you might first think, because if it's off-screen to the left, we still want it able to move right (just not left).
So we need to think of four separate scenarios. Read the interleaved comments to understand how it works.
MySprite.prototype.Do_Frame_Things = function() {
// if the x-velocity is to the left, only apply the velocity if the sprite is not off-screen to the left
if ((this.velocity_x < 0) && (this.x > 0)) this.x = this.x + this.velocity_x;
// if the x-velocity is to the right, only apply the velocity if the sprite is not off-screen to the right
if ((this.velocity_x > 0) && (this.x + this.MyImg.width < myCanvas.width )) this.x = this.x + this.velocity_x;
// if the y-velocity is upward, only apply the velocity if the sprite is not off-screen at the top
if ((this.velocity_y < 0) && (this.y > 0)) this.y = this.y + this.velocity_y;
// if the y-velocity is downward, only apply the velocity if the sprite is not off-screen at the bottom
if ((this.velocity_y > 0) && (this.y + this.MyImg.height< myCanvas.height)) this.y = this.y + this.velocity_y;
if (this.visible) ctx.drawImage(this.MyImg, this.x, this.y); // draw the thing
}
Don't worry about remembering how to create something like this yourself from a standing-start ... you can
just copy and paste code fragments from S2JS and adapt them to your needs.
The important thing is you understand how they work.
Recall the "&&" operator is like the "and" block in Scratch