Random Ball Speed in P5.js

时间:2016-10-20 13:06:38

标签: javascript random p5.js

I have the following code:

var posX1 = 0, posY1 = 100;
var speedX1 = random(1,3), speedY1 = random(1,3);

var posX2 = 0, posY2 = 200;
var speedX2 = 2, speedY2 = 0;

function setup()
{
    createCanvas(640, 480);
}

function draw()
{
    // redraw the background so you blank the screen
    background(255);

    if(posX1 > width)
    {
      speedX1 = -speedX1;
    }

    // update the position based on the speed
    posX1 += speedX1;
    posY1 += speedY1;

    // draw a ball
    strokeWeight(20);
    point(posX1, posY1);

    //
    posX2 += speedX2;
    posY2 += speedY2;

    //draw a ball
    strokeWeight(20);
    point(posX2, posY2);


}

Its in P5. I basically want the two circles to race each other at random speeds between 1 and 3 but instead they dont even appear on the screen. Can anyone point out where I'm going wrong?

1 个答案:

答案 0 :(得分:2)

You can't use P5.js functions before setup() is called.

If you run this code and look at the JavaScript console (which should always be your first step) you'll see that you're getting an error saying that random() is not defined. If you then Google that error, you'll get a ton of results explaining what's going on.

From the P5.js FAQ:

Why can't I assign variables using p5 functions and variables before setup()?

The explanation for this is a little complicated, but it has to do with the way the library is setup in order to support both global and instance mode. To understand what's happening, let's first look at the order things happen when a page with p5 is loaded (in global mode).

  1. Scripts in <head> are loaded.
  2. <body> of HTML page loads (when this is complete, the onload event fires, which then triggers step 3).
  3. p5 is started, all functions are added to the global namespace.

So the issue is that the scripts are loaded and evaluated before p5 is started, when it's not yet aware of the p5 variables. If we try to call them here, they will cause an error. However, when we use p5 function calls inside setup() and draw() this is ok, because the browser doesn't look inside functions when the scripts are first loaded. This is because the setup() and draw() functions are not called in the user code, they are only defined, so the stuff inside of them isn't run or evaluated yet.

It's not until p5 is started up that the setup() function is actually run (p5 calls it for you), and at this point, the p5 functions exist in the global namespace.

In other words, you have to define your variables at the top of your sketch, but only assign them inside the setup() function:

var speedX1;
var speedY1;

function setup()
{
    createCanvas(640, 480);

    speedX1 = random(1,3);
    speedY1 = random(1,3);
}