Tap the arrow keys to move the sixteen ellipses left to right.
A fork of Unit 3, Lab 2 - Moving Wave by Michael Condiracci
Hi Michael, thought I'd make this a tutorial so I could walk through a couple changes. First, you don't need to use `translate` to achieve the change—you can simply change the `xStart` variable (which you're already doing, just within the context of `translate`). Specifically, I can change:
translate (xStart = xStart - 4,0);
to...
xStart = xStart - 4;
The code that is inside `keyPressed()` can be put inside of an `if` statement inside of the draw function, using `keyIsPressed`. So this:
function keyPressed() {
if (keyCode === LEFT_ARROW) { //Left arrow commands
xStart = xStart - 4;
} else if (keyCode === RIGHT_ARROW) { //Right arrow commands
xStart = xStart + 4;
}
}
becomes this:
if (keyIsPressed) {
if (keyCode === LEFT_ARROW) { //Left arrow commands
xStart = xStart - 4;
} else if (keyCode === RIGHT_ARROW) { //Right arrow commands
xStart = xStart + 4;
}
}
Which allows for smoother movement because it's being checked every frame, instead of just the frame in which the key goes from up to down.
var angle;
var easing = 0.01;
var xStart = 25;
var yOffset;
var speed = 0.1;
var LeftArrowPressed;
var RightArrowPressed;
function setup() {
createCanvas(1000, 500);
angle = 0;
}
function draw() {
yOffset = 100;
background(180);
var y = yOffset + sin(angle + 0.0) * 50;
var y2 = yOffset + sin(angle + 0.4) * 50;
var y3 = yOffset + sin(angle + 0.8) * 50;
for (var i = 0; i < 16; i++) {
y = yOffset + sin(angle + i * 0.4) * 50; //y pattern: angle + i * 0.4;
var x = xStart + i * 60; //x pattern: increases by 60;
ellipse(x, y, 50);
}
angle += speed;
}
function keyPressed() {
if (keyCode === LEFT_ARROW) { //Left arrow commands
xStart = xStart - 4;
} else if (keyCode === RIGHT_ARROW) { //Right arrow commands
xStart = xStart + 4;
}
}
//function keyPressed() {
// if (keyCode === LEFT_ARROW) {
// LeftArrowPressed = 1;
// } else if (keyCode === RIGHT_ARROW) {
// RightArrowPressed = 1;
// }
//}
//function keyReleased() {
// if (keyCode === LEFT_ARROW) {
// LeftArrowPressed = 0;
//} else if (keyCode === RIGHT_ARROW) {
// RightArrowPressed = 0;
//}
//while (LeftArrowPressed = 1) {
// translate (xStart--, 0);}
// while (RightArrowPressed = 1){
// translate (xStart++, 0);}