-1
\$\begingroup\$

Okay, so if I use this code to randomly spawn balls at the top of the screen, how do i get them to move down:

var max_bollar = 10;
var i = 0;
var timecounter = 0;
var bollarcounter = 0;
var spawn_delay = 200;
var min_spawn_delay = 25;
var max_spawn_delay = 500;

function spawn(i)
{
    var boll = {x: random(totalWidth), y: random(totalHeight)}
    circle( boll.x, 10, 10, "blue");
    timecounter = 0;
    bollarcounter++;
    max_spawn_delay = ( random(max_spawn_delay - min_spawn_delay ) + min_spawn_delay );
}

function update()
{
    timecounter += 1;
    if(timecounter == spawn_delay && bollarcounter < max_bollar) spawn(bollarcounter);
}

I want them to be falling from the top of the screen and the player has to dodge the balls falling. How do I make the balls move or rather how do I get the information of each ball? So I can Add y cordinates and stuff. (I know i need to Add a clearScreen to make the balls move)

I want to make something like this:

Boll.y += 10;
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

Create an array to hold all the balls:

var balls = [];

When you spawn a ball, include it on the list:

function spawn(i)
{
    var boll = {x: random(totalWidth), y: random(totalHeight)}
    circle( boll.x, 10, 10, "blue");
    timecounter = 0;
    bollarcounter++;
    max_spawn_delay = ( random(max_spawn_delay - min_spawn_delay ) + min_spawn_delay );

    // Include the ball on the list
    balls.push(boll);
}

Now is very easy to control them, just iterate the array of the balls in the update method and do the changes you want:

for (var i = 0; i < balls.length; i++) {
    balls[i].y += 5;
};
\$\endgroup\$
5
  • \$\begingroup\$ koda.nu/labbet/6356038 what did i do wrong the balls did not go down \$\endgroup\$
    – Samuel
    Commented Feb 10, 2016 at 19:42
  • \$\begingroup\$ You are not doing as I said, the update method is wrong. You need use a use a for loop to interate through the array. You aren't clearing the screen and aren't drawing the balls again. See the changes on the link. \$\endgroup\$ Commented Feb 10, 2016 at 19:57
  • \$\begingroup\$ Okay Thanks, i am new to coding so i don't get everithing \$\endgroup\$
    – Samuel
    Commented Feb 10, 2016 at 20:00
  • \$\begingroup\$ Is there any way to make the all balls fall from the top? If there is not I'M happy anyways \$\endgroup\$
    – Samuel
    Commented Feb 10, 2016 at 20:04
  • \$\begingroup\$ In the spawm method, set the y to 0. \$\endgroup\$ Commented Feb 10, 2016 at 20:11
0
\$\begingroup\$
  1. Add the balls to the list
  2. in update() iterate over the list and update each ball's y position
\$\endgroup\$
2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .