Need Help With keyTyped in P5

Hi! I’m having an issue with my code. I’m making a dress up game and her hair and outfits are supposed to change whenever you press a key, but it’s not working!

Here’s the code:

let dg1;
let dghair1;
let dghair2;
let dghair3;
let dgoutfit1;
let dgoutfit2;
let dgoutfit3;

function preload () {
dg1 = loadImage(“dg1.png”);
dghair1 = loadImage(“dghair1.png”);
dghair2 = loadImage(“dghair2.png”);
dghair3 = loadImage(“dghair3.png”);
dgoutfit1 = loadImage(“dgoutfit1.png”);
dgoutfit2 = loadImage(“dgoutfit2.png”);
dgoutfit3 = loadImage(“dgoutfit3.png”);
}

function setup() {
createCanvas(600, 600);
image(dg1, 0, 0);
dgmusic = createAudio(“dgmusic.mp3”);
dgmusic.autoplay(true);
dgmusic.loop();
}

function keyTyped() {
if (key === ‘q’) {
image(dghair1, 0, 0);
dghair1.resize (600, 600);
} else if (key === ‘w’) {
image(dghair2, 0, 0);
} else if (key === ‘e’) {
image(dghair3, 0, 0);
} else if (key === ‘a’) {
image(dgoutfit1, 0, 0);
} else if (key === ‘s’) {
image(dgoutfit2, 0, 0);
} else if (key === ‘d’) {
image (dgoutfit3, 0, 0);
}
}

It’s nice to read properly formatted code. Use ``` before and after the code to format it (or just select it and click the proper button, it looks like </> ).
There’s no draw() function in your code, so there is no loop. The things in setup() happens and the program stops. If you want to listen for keys, you need to add function draw(){///stuff to draw here}
If you like the images to persist trough draw loop when you release the key, you will need to use some booleans to be changed by the keys, other wise the images will display only when you are pressing the key.
This overview covers the basics of how the setup and draw works.

1 Like