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
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.
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):