We are about to switch to a new forum software. Until then we have removed the registration on this forum.
When I press 2 keys at the same time, and then release the second key (and keep pressing the first key), processing gets that I still im pressing the second key, but not the first.
I am using Processing 3.3.6 and Windows 10.
How can I fix this?
How to replicate:
The code:
Main class:
int maximosDisparos = 10;
Jugador jugador;
Disparo[] disparos = new Disparo[maximosDisparos];
void setup() {
size(640, 360);
jugador = new Jugador();
for (int i = 0; i < disparos.length; i++) {
disparos[i] = new Disparo();
}
}
void draw() {
background(0);
jugador.borde();
jugador.mover();
jugador.disparar();
for (int i = 0; i < disparos.length; i++) {
disparos[i].subir();
disparos[i].dibujar();
}
jugador.dibujar();
}
Disparo class:
class Disparo {
int anchura = 4;
int altura = 20;
float velocidad = 10;
PVector posicion = new PVector(0, -altura - anchura / 4);
void subir() {
if (posicion.y > -altura - anchura / 2) {
posicion.y -= velocidad;
}
}
void dibujar() {
stroke(255);
strokeWeight(anchura);
line(posicion.x, posicion.y, posicion.x, posicion.y + altura);
}
}
Jugador class:
class Jugador {
int anchura = 50;
int altura = 4;
int numeroDisparos;
float siguienteDisparo;
PVector posicion = new PVector(width / 2, height - 25);
void borde() {
if (posicion.x >= width + anchura / 2) {
posicion.x = -anchura / 2 + 1;
}
if (posicion.x <= -anchura / 2) {
posicion.x = width + anchura / 2 - 1;
}
}
void mover() {
if (keyPressed) {
if (key == 'a') {
posicion.x -= 5;
}
if (key == 'd') {
posicion.x += 5;
}
}
}
void disparar() {
if (millis() > siguienteDisparo) {
siguienteDisparo = millis() + 250;
if (keyPressed) {
if (key == ' ') {
disparos[numeroDisparos++ % maximosDisparos].posicion = new PVector(posicion.x, posicion.y);
}
}
}
}
void dibujar() {
stroke(255);
strokeWeight(altura);
line(posicion.x - anchura / 2, posicion.y, posicion.x + anchura / 2, posicion.y);
}
}
Sorry for the spanish in the declarations, and sorry if bad english.
Answers
key
stores the value for the last key that the user has interacted with. If you want to track multiple keys being pressed and released, you need to stop using the keyPressed boolean and start using the functions keyPressed() and keyReleased(). In those functions, store information in an array about the new state of the key, and then refer to that array in any logic that relies on which keys are being pressed.http://Studio.ProcessingTogether.com/sp/pad/export/ro.91tcpPtI9LrXp
here a red text shows what goes on in your original sketch: