Okay, so in code.org's game lab, they offer a pre-made function called "line();" which should draw a line stemming from a given x1 y1, and x2 y2 coordinate. When I attempted to create a for-loop that would allow me to draw 3 line segments on the same y pixel, the for-loop simply ran forever inside the draw loop, (but not correctly, it just moved the x2 and y2 to the right infinitely), so I moved it outside of the draw loop and now I'm getting no output at all...
var spaceXPos = 70;
var spaceXPos2 = spaceXPos + 25;
for (var i = 0; i < 4; i++){
stroke(rgb(255, 255, 255));
strokeWeight(2);
line(spaceXPos, 200, spaceXPos2, 200);
spaceXPos = spaceXPos + 20;
}
function draw() {
background("wheat");
}
This is for an independent project, I'm using code.org because it offers an easy-to-use screen for animations and drawing, and I'm also taking an AP CompSci class through it as well.
Here's a link to this code in the Game Lab https://studio.code.org/projects/gamelab/_w391nq3oEo62S3WOOpWg6NrMrMHNvo8n20gVMDu5hg
When your
line()command is outside of the draw loop, as in the sample code you posted, the following happens, in order:forloop, which ends up callingline()four times.draw()function callsbackground("wheat"), painting over the output of your setup code. This happens many times each second.So you see no output (except for the background color) because your
draw()function is painting over the lines yourforloop drew.If, as you describe above, you move the
forloop intodraw()so that your code looks like this:...then the following happens:
spaceXPosis set to 70 andspaceXPos2is set to 95.Draw (first time): The background is drawn, and then your lines are drawn. Every time you draw a line you are adding 20 to
spaceXPos, butspaceXPos2is not changing, so the four lines drawn in the first draw call are:line(70, 200, 95, 200)line(90, 200, 95, 200)line(110, 200, 95, 200)line(130, 200, 95, 200)Draw (second time): The background is drawn again, and then your lines are drawn again. However, the value of
spaceXPosdidn't get reset, so it keeps moving to the right. Notice that thex2value 95 hasn't changed, so one end of the line is staying in the same place.line(150, 200, 95, 200)line(170, 200, 95, 200)line(190, 200, 95, 200)line(210, 200, 95, 200)Draw (and so on): One end of the line keeps moving to the right until it's off the screen, and no more changes are visible, so you end up with something like this:
If your goal is to draw three line segments in a row, you'll need to make sure both the x1 and x2 values change for each call, and make sure they start in the same place on every draw call. Here's one way to do that: