I have something wrong with my for statement.

Can anyone explain why this code isn't making any rectangles? :

function setup() {
createCanvas(640, 480);
background(51);
console.clear;
var i = 0;
}


var Noclip = false;
var X = 00
var Y = 00

function draw() {
drawmap(1,false);
}


function NoClip() {
switch(Noclip) {
    case true:
        Noclip = false
document.getElementById("NoClipState").innerHTML = "NoClip Disabled";
        break;
    case false:
        Noclip = true
document.getElementById("NoClipState").innerHTML = "NoClip Enabled";
        break;
} 
}

function drawmap(N,S) {
fill(0);
if (N === 1) {
if (S === false){
noStroke();
} else if (S === true) {
stroke(255);
}
for (var i = 0; i == 640; i + 40) {
rect(X + i,Y,40,40);
console.log(i);
}
}
}

This is using the p5.js library and it works until it is supposed to make the rectangles, then it does nothing, also if I put "i" into the console to check its value, I get 22. I don't know what's going on.

Answers

  • Answer ✓

    Found my error... apparently I needed

    for (i = 0; i < 640; i++) { 
    rect(X + i * 40,Y,40,40);
    console.log(i);
    } 
    

    idk why this works, but it does

  • edited January 2018 Answer ✓

    the condition

    you had this wrong: for (var i = 0; i == 640; i + 40) {

    especially i == 640 where you already remarked you need: i < 640 instead

    reason is that the condition i < 640 must be true to keep the for loop running

    With i == 640 he condition is not true and the for loop is just skipped, with i < 640 the condition is met (until after 640 times, when i reaches 640)

    The other issue

    The other issue was i + 40 which does nothing (we don't assign a new value to i so it stays 0 I think). You need i = i+40 here, which you can write as i+=40 as well.

    i++ changes the value of i as well.

    Link

    see

    https://www.processing.org/reference/for.html

    and the whole reference:

    https://www.processing.org/reference/

Sign In or Register to comment.