Always Sunny Always Sunny - 1 year ago 92
Javascript Question

Tracking Y axis end value and apply some logic

I was playing with processing js on khan academy. I have stucked on a point to apply my logic to make the drops start back at the top once they've reached the bottom, using a conditional. I just need to track the

Y axis
endpoint and call my
to apply re rain ability.

var xPositions = [];
var yPositions = [];

var setXYPositions = function(){

for(var i = 0 ; i <= 400 ; i+=10 ){

//call rain

draw = function() {

background(204, 247, 255);

for (var i = 0; i < xPositions.length; i++) {
fill(random(2,255), random(2,255), random(2,255));
ellipse(xPositions[i], yPositions[i], 10, 10);
yPositions[i] += 5;


Answer Source

How do you know when a yPosition index has reached the bottom of the sketch area? What value does it have when that happens?

To find this out, try using just a single yPosition instead of 40 of them. Print out the yPosition, and figure out what it is when it goes off the bottom of the screen.

Thinking about it another way: it looks like you're using the default size of 100x100, meaning the height of your window is 100 pixels. If the yPosition of the top of the window is 0, what is the yPosition of the bottom of the window?

Hopefully that helped you figure out that the bottom yPosition of the window is 100. Now that you know what, what do you want to do when a circle reaches that? You want it to reset to the top of the window, right? Well, what's the yPosition of the top of the window? We already said that it was zero!

Putting it all together, it looks like this:

yPositions[i] += 5;
if(yPositions[i] > 100){
   yPositions[i] = 0;

What happens if you change the size of the window (by calling the size() function from setup())? We'd have to change the 100 in that if statement. But Processing actually makes our lives easier by giving us a height variable that we can use instead!

yPositions[i] += 5;
if(yPositions[i] > height){
   yPositions[i] = 0;

Now our code will work no matter what size the window is.

Shameless self-promotion: I've written a tutorial covering animation and resetting positions available here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download