xxxxxxxxxx
90
// stuff i need
// bouncing ball
// paddle that doesn't go off the screen
// need the bouncing ball code that i've already written
// however, also need a check that
const ball = {
x: 10,
y: 200,
speedX: 2,
speedY: 2,
d: 10
};
const paddle = {
w: 20,
h: 80,
x: 100,
y: 100
}
let score = 0;
function setup() {
createCanvas(400, 400);
rectMode(CENTER);
paddle.x = width-50;
paddle.y = height/2;
}
function draw() {
background(220);
drawPaddle();
updatePaddle();
drawBall();
updateBall();
drawScore();
}
function drawPaddle() {
rect(paddle.x, paddle.y, paddle.w, paddle.h);
}
function updatePaddle() {
paddle.y = constrain(mouseY, paddle.h/2, height-paddle.h/2);
}
function drawBall() {
circle(ball.x, ball.y, ball.d);
}
function updateBall() {
ball.x += ball.speedX;
ball.y += ball.speedY;
if (ball.x < ball.d/2) {
ball.speedX = -ball.speedX;
}
if (ball.y < ball.d/2 || ball.y > height-ball.d/2) {
ball.speedY = -ball.speedY;
}
// need to, in here, check if paddle and ball are intersecting
if (ball.x + ball.d/2 > paddle.x - paddle.w/2 &&
ball.y > paddle.y - paddle.h/2 &&
ball.y < paddle.y + paddle.h/2) {
ball.speedX = -ball.speedX;
updateScore();
}
if (ball.x > width + ball.d/2) {
ball.x = ball.d/2;
ball.y = random(ball.d/2, height-ball.d/2);
ball.speedX = random(0, 3);
ball.speedY = random(-2, 2);
}
// ball speedY also depends on the speed that the user is
// moving the paddle
}
function updateScore() {
score += 1;
}
function drawScore() {
text("Score: " + score, 10, 20);
}