Skip to content

Instantly share code, notes, and snippets.

@dshen6
Last active March 8, 2018 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dshen6/1dc13136b7efab195f5bf7bae07e1d1e to your computer and use it in GitHub Desktop.
Save dshen6/1dc13136b7efab195f5bf7bae07e1d1e to your computer and use it in GitHub Desktop.
Exported from Popcode. Click to import: https://popcode.org/?gist=1dc13136b7efab195f5bf7bae07e1d1e

Now you have all the tools to make a game!

But let's just practice using them for now.

  1. What variable do you change to make the ball fall faster? Try it!
  2. What variable can you change to make the ball fall further?
  3. Let's give our ball horizontal motion!
  • Create a global var horizontalSpeed, assign it the value 1.
  • Within the move function body, make another variable called previousLeft, assign it ball.offset().left.
  • Then use offset() to change the ball's left offset.
  1. Your ball will move right forever unless we stop it.
  • Make a global var maxLeft, assign it the value 400.
  • Within the move function body, use a conditional statement to only increase our left offset if our previousLeft is less than maxLeft.
  1. Let's make our ball respond to input.
  • Uncomment the last 8 lines.
  • Change the value of horizontalSpeed when the right/left arrow keys are tapped. What happens if horizontalSpeed is a negative value?
  1. When you've gotten this far, give one of your teachers a high-five so we know you're finished! Then rock on below...

Extensions

  1. Make the ball bounce up and down.
  • When the ball hits maxTop, set gravitySpeed = -gravitySpeed. Why does this work?
  • Create a minTop variable, assign it a value you choose.
  • Use another conditional statement to give the ball a ceiling.
  • How can you make the ball gradually lose height after multiple bounces?
  1. Give the ball a random direction using Math.random() when the user clicks anywhere on the page.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div class="ball"></div>
</body>
</html>
{"enabledLibraries":["jquery"],"hiddenUIComponents":["console","editor.html","editor.css"]}
var ball = $(".ball");
// let's center our ball in the screen by using offset
ball.offset({left: 400});
// then let's make it fall
var gravitySpeed = 1;
var maxTop = 400;
function move() {
var previousTop = ball.offset().top;
if (previousTop <= maxTop) {
ball.offset({top: previousTop + gravitySpeed});
}
}
setInterval(function() {
move();
}, 17);
// $("body").keydown(function(e) {
// if (e.key === "ArrowRight") {
// // change horizontalSpeed
// }
// if (e.key === "ArrowLeft") {
// // change horizontalSpeed (try negative numbers)
// }
// });
.ball {
border-radius: 50%;
width: 20px;
height: 20px;
background: green;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment