Individualize functions in P5.js

homework policy * asking questions

Hello programmers i have a question about my program, i created a program who draw a ball, add animation to her and a text. I only need call one function to make all it. But now, i need individualize those balls, i have an random variable to display the ball in random locations, but calling two or more balls then do not appears in diferents locations, its the same place of the first ball :frowning:

I need help to individualize those balls, but i dont know how i start. Can you help me?

let ballX = 40;
let ballY;
let speed = 5;
function setup() {
  createCanvas(490, 465);
  ballY = random(50, 390);
}
function draw() {
  background(210);
  function drawBall() {
     function displayText() {
       fill('black')
       textSize(25)
       text("A ball is run now", ballX + 25, ballY - 25);
     };
     function form() {
       noStroke()
       fill('red')
       ellipse(ballX, ballY, 50, 50);
     };
    ballX += speed
    if (ballX >= 445) {
      speed = -5;
    };
    if (ballX <= 40) {
          speed = 5;
        };
    displayText()
    form()
  };
    drawBall()
};

Thanks by your atencion, i will put screenshots or a video later.

1 Like

Hi @Kevincroos,

First of all one thing about your code:

You shouldn’t put the drawBall() function (and others) inside the draw() function because it’s not optimized and it’s not needed in the current configuration since the function will always be the same. As stated in the following website:

Unlike other types of values, functions typically don’t change; a function is created to perform a specific task. So it doesn’t make much sense to waste CPU cycles recreating a somewhat static value over and over again.

Aah! this is exactly the purpose of Object-oriented programming: being able to represent your data as units of data (called objects).

Check a previous thread I did on the subject (with balls but in Java, it shouldn’t be too hard to do it in JS):

Also see MDN’s documentation on the subject:

2 Likes

Although written for Processing’s Java Mode these 2 OOP articles can be easily applied to any Processing flavor:

  1. From several variables to arrays - Processing 2.x and 3.x Forum
  2. From several arrays to classes - Processing 2.x and 3.x Forum

This is how we create classes in JS btW:

3 Likes

Hello again Joseph, thank you i will read these articles. Yours explanations its very good.

1 Like

Hello, thanks by your help too, i will read your articles.

I was able to solve this problem using the examples written in Java. Thanks a lot

3 Likes