Creating "boundaries" for my ball using max and min

So I was supposed to create this joystick like program in one of my questions but Im not sure how I can use functions max and min so the ball doesnt fly past the canvas when Im controlling it with my mouse.

float lineX = width/2;
float lineY = height/2;
float ballX = width/2;
float ballY = height/2;
final float DIAMETER_BALL = 20;
float moveX = mouseX-250;
float moveY = mouseY-250;
final float SPEED_OF_BALL = 1.2;

void setup() {

void draw() {

void drawBall() {
ballX = width/2;
ballY = height/2;
ballX = (ballX + moveX);
ballY = (ballY + moveY);
ellipse((ballX+moveX), (ballY+moveY), DIAMETER_BALL, DIAMETER_BALL);

void drawLine() {
lineX = width/2;
lineY = height/2;
line(lineX, lineY-150, lineX, lineY+150);
line(lineX-150, lineY, lineX+150, lineY);

void moveBall() {
moveX = (mouseX-250) / SPEED_OF_BALL;
moveY = (mouseY-250) / SPEED_OF_BALL;

Check the examples in the main page.This one would be helpful: Bounce / Examples /

One point to watch:

The values of mouseX and mouseY are only available within setup() and draw(). You can define those variables globals but you need to assign their values in setup.

I recommend that instead of using 250 you sue width/2 and height/2. this is easier to read and in case you change your sketch size, you don’t have to update all these “magic numbers”.

Finally, I like to say I do not fully understand what your function drawBall() does.

Related to your question, can you use constrain() instead?


Sorry, Im new to programming and I have to use max and min functions specifically in the problem. The drawBall() function is supposed to move the ball to a direction based on the mouse.

In general, when the ball is moving along the x axis and it reaches the left boundary (the width of you sketch) then you use something like posX=min(width,posX) which would return the min of the two values and assign it back to your posX. However, you will need to detect when this happens as you will need to reverse the velocity along the x axis as well so it “bounces back”.


1 Like