Anyone ever give the students an extra challenge of trying to figure out how to keep the rectangle from never leaving the screen. I feel this would be a good key learning as if you were designing a game and say the rectangle was a character I feel you would never want any part of it at all to leave the screen.
Anyways hope this makes sense and here is a solution to this…
// Create a sprite
var sprite = createSprite(200, 100, 50, 50);
sprite.shapeColor = “red”;
function draw() {
background(“white”);
// Move the sprite in the direction of the arrow keys
// But make sure it doesn’t go off the screen
if (keyDown(“up”) && sprite.y > 25) {
sprite.y = sprite.y - 5;
}
if (keyDown(“down”) && sprite.y < 375) {
sprite.y = sprite.y + 5;
}
if (keyDown(“left”) && sprite.x > 25) {
sprite.x = sprite.x - 5;
}
if (keyDown(“right”) && sprite.x < 375) {
sprite.x = sprite.x + 5;
}
drawSprites();
}