To see the complete code and running sketch click here.
To see the complete code and running sketch click here.
Description
In LA 1 we had a ball move up, down, left and right. In this final project, we apply this motion to our existing happy face drawing, and then add interactivity: by pressing different keys, the user can control the direction in which the smiley moves.
Steps Outline
Learning Activities Reference
Step by Step
Let's start from the code from LA 4.2 , at the end of step 2. We had an ellipse that could move in both the x and y axes, depending on the values of the speedX
and speedY
variables. Try it on the p5 editor:
var x = 0;
var y = 60;
var speedX = 1;
var speedY = 0;
function setup() {
createCanvas(600, 400);
}
function draw() {
background(0);
x = x + speedX;
y = y + speedY;
ellipse(x, y, 20, 20);
}
Now, just like we did in LA 3.4 to trigger sounds, let's add a keyPressed function. Depending on the key the user presses, we should change the values of speedX
and speedY
.
speedX = -1
)speedX = 1
)speedY = -1
)speedY = 1
)Add the function below to the code from the previous step. And it should just work! We don't need to change anything in our draw loop. This is because keyPressed updates the same variables that our existing draw loop is using. What happens is the user presses a key, keyPressed is called and updates speedX and speedY accordingly, and the next time the draw function runs, it accesses these updated speeds.
function keyPressed() {
if (key === 'J') { //move left
speedX = -1;
speedY = 0;
}
else if (key === 'L') { //move right
speedX = 1;
speedY = 0;
}
else if (key === 'I') { //move up
speedX = 0;
speedY = -1;
}
else if (key === 'K') { //move down
speedX = 0;
speedY = 1;
}
}
Notice that when the smiley is moving right or left, it shouldn't move vertically, so we also set speedY
to 0. If the smiley is moving up or down, we should set speedX
to 0. What would happen if we skip this step?
Finally, we need to replace the ellipse with our smiley face. Here is the code we had from LA 4.1:
//Face
fill(249,205,173);//rosy beige
ellipse(x, y, 100, 100);
//Eye 1
fill(30);//dark gray
ellipse(x, y+10, 10, 10);
//Eye 2
ellipse(x+15, y+10, 10, 10);
//Mouth
fill(252,157,154);//light pink
arc(x, y+25, 30, 30, 0, radians(180), PIE);
Since in that sketch we were also using variables called x
and y
for positioning the smiley face, we can just paste this code where this line was in step 1: ellipse(x, y, 20, 20);
. Try it! Now you can tweak the colors, stroke weight, and so on.
Can you make the smiley stop when it reaches the edges of the screen? (tip: take a look at the if statement in LA 1 step 1 as a reference)
Can you replace the smiley face with a drawing you made in Unit 1?