I am doing a small assignment that requires the following:
I have to create a while-loop that draws 30 lines on-screen. Line number 7 and line number 23 should be colored red.
Because I am still trying to figure things out, I try to color the 2 nearest lines from stroke(0); to stroke(255);, but no matter what I try, I cannot get the 2 lines to change color
In this example I tried nesting a while loop, which so far doesn’t work. I also tried removing te nested while loop and add an “if” statement with the same variables (x == 40 && x == 60) but still nothings happens. What can I do to fix this?
var x = 20;
var stap = 20;
var stop = 600;
function setup () {
createCanvas (700, 700);
}
function draw () {
stroke(0);
while(x < stop) {
line(x, 60, x, 80);
x += stap;
while (x == 40 && x == 60) {
stroke(255);
}
}
}
Processing, and I strongly believe P5.js as well, only update their screens at the end of the draw loop
You’re changing the stroke AFTER you draw the line, then draw restarts, set stroke to 0 and draws again
while (or if for that matter) x == 40 AND x == 60 never happens. x cannot be both 40 And 60 at the same time, use or: ||
Here’s your code with the proper changes, but note it does not draw all the lines at once, for that you’d need to store the x values in an array of some sorts and use a for loop to draw them
var x = 20;
var stap = 20;
var stop = 600;
function setup () {
createcanvas(700, 700);
}
function draw () {
stroke(0);
if (x < stop) {
if (x == 40 || x == 60) {
stroke(255);
}
line(x, 60, x, 80);
x += stap;
}
}
I added the ‘while’ loop that I needed for my assignment to it
while (x < stop) {
stroke(0);
if (x == 40 || x == 60) {
stroke(255);
}
line(x, 60, x, 80);
x += stap;
}
}
and got the desired effect I was looking for :).
Sorry if the question is stupid, but could you tell me why I cannot put the
line(x, 60, x, 80);
x += stap;
right under the x<stop equation, and before the if (x== 40 …)
like:
while (x < stop ) {
stroke(0);
line(x, 60, x, 80);
x += stap;
if (x == 40 || x == 60) {
stroke(255);
}
}
}
it just seems like it is in the same position either way (as in being inside the while loop) but just getting added later. Or does it need to do the equation/counting first before it should draw?
If you post to multiple sites, please link between those posts so we know what help you’ve already received. This question has also been asked (and answered) here:
Sorry about that. I am used to the fact that I sometimes do not get a response on 1 site, which makes me inclined to post it on another for good meassure.
When i got my first answer on stackoverflow, it unfortunately wasnt the answer I could use (actual javascript and not P5) and later on got the answer here before others started to comment i believe.
But wont happen again. Will stick it to 1 post at a time.