Skip to content

Instantly share code, notes, and snippets.

@LiorB-D
Created December 23, 2021 03:24
Show Gist options
  • Select an option

  • Save LiorB-D/d0dc6f8028b761390f3ec5451dd4493e to your computer and use it in GitHub Desktop.

Select an option

Save LiorB-D/d0dc6f8028b761390f3ec5451dd4493e to your computer and use it in GitHub Desktop.
<!-- Pull in P5.JS graphics library -->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"
integrity="sha512-WIklPM6qPCIp6d3fSSr90j+1unQHUOoWDS4sdTiR8gxUTnyZ8S2Mr8e10sKKJ/bhJgpAa/qG068RDkg6fIlNFA=="
crossorigin="anonymous"
></script>
<script>
const screenDim = 500;
let ball = { x: 250, y: 100, vx: 2, vy: 2 };
let play1 = { x: 30, y: 250, height: 100, width: 20 };
let play2 = { x: screenDim - 50, y: 250, height: 100, width: 20 };
function setup() { // Runs on startup
frameRate(100);
createCanvas(screenDim, screenDim);
}
function draw() { // Runs on loop according to frameRate
fill("transparent");
rect(0, 0, screenDim, screenDim); // Draw the box around our game
// Draw ball
fill("red");
ellipse(ball.x, ball.y, 10, 10);
// Draw paddles
fill("black");
rect(play1.x, play1.y, play1.width, play1.height);
rect(play2.x, play2.y, play2.width, play2.height);
if (ball.y > screenDim - 10 || ball.y < 10) { // Bounce off top and bottom
ball.vy *= -1;
}
if ( // If intersecting with Paddle #1
ball.x < play1.x + play1.width + 10 &&
ball.y > play1.y &&
ball.y < play1.y + play1.height
) {
ball.vx *= -1.1; // Invert and increase velocity by 10%
ball.vy = random(8) - 4; // Random y velocity between -4 and 4
}
if ( // If intersecting with Paddle #2
ball.x > play2.x - 10 && // If it
ball.y > play2.y &&
ball.y < play2.y + play2.height
) {
ball.vx *= -1.1; // Invert and increase velocity by 10%
ball.vy = random(8) - 4; // Random y velocity between -4 and 4
}
// Move Paddles
if (keyIsDown(87) && play1.y > 5) { // W is pressed
play1.y -= 4;
}
if (keyIsDown(83) && play1.y < screenDim - play1.height) { // S is pressed
play1.y += 4;
}
if (keyIsDown(UP_ARROW) && play2.y > 5) {
play2.y -= 4;
}
if (keyIsDown(DOWN_ARROW) && play2.y < screenDim - play1.height) {
play2.y += 4;
}
// Move the ball
ball.x += ball.vx;
ball.y += ball.vy;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment