0

I am teaching kids about the basic and simplest way of designing and coding the Pong Game via Javascript in the p5 editor. I just have a question regarding the initial phase of designing.

The code is as follows:

function setup()

{
    createCanvas(400,400);
}

function draw()

{
    background('black');
    rect(20,160,10,80);
    rect(195,195,10,10);
    rect(380,mouseY,10,80);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

The first rect function is for the computer paddle controlled by AI. The second rect function is for the ball. The third rect function is for the player paddle.

I am using mouseY for the vertical movement but the paddle is going out of the canvas of dimension 400*400 towards the lower part of the canvas.

Without using any function and via simple addition/subtraction of the various numerical coordinates involved in this code, how can I prevent the player paddle from moving out of the canvas?

James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

1

You have to limit the y coordinate of the paddle to the range [0, height-80]. height is a built in variable containing the height of the canvas and the height of the paddle is 80.

function setup() {
    createCanvas(400,400);
}

function draw() {
    background('black');
    rect(20,160,10,80);
    rect(195,195,10,10);

    let y = mouseY;
    if (y < 0)
        y = 0;
    if (y+80 > height)
        y = height-80;
    rect(380,y,10,80);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

This can be further improved by using min and max:

function setup() {
    createCanvas(400,400);
}

function draw() {
    background('black');
    rect(20,160,10,80);
    rect(195,195,10,10);

    let y = max(0, min(height-80, mouseY));
    rect(380,y,10,80);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
Rabbid76
  • 202,892
  • 27
  • 131
  • 174