processing / p5.js

p5.js is a client-side JS platform that empowers artists, designers, students, and anyone to learn to code and express themselves creatively on the web. It is based on the core principles of Processing. http://twitter.com/p5xjs —
http://p5js.org/
GNU Lesser General Public License v2.1
21.73k stars 3.34k forks source link

keyPressed event does only work for the first of multiple sketches #1492

Closed good-grief closed 8 years ago

good-grief commented 8 years ago

In a scenario with multiple sketches the keyPressed-event is only received by the first sketch. This behavior is not similar to other events (e.g. mouseClicked).

Here is some code to demonstrate the problem:

var sketch1 = function( p ) {

  p.setup = function() {
    console.log("Setup sketch 1");
    p.createCanvas(700, 410);
  };

  p.draw = function() {
    p.background(0);
    p.fill(255);
    p.ellipse(100,100,50,50);
  };

  p.keyPressed = function() {
    console.log("keyPressed sketch1");
  }

  p.mouseClicked = function() {
    console.log("mouseClicked sketch1");
  }
};

var sketch2 = function( p ) {

  p.setup = function() {
    console.log("Setup sketch 2");
    p.createCanvas(700, 410);
  };

  p.draw = function() {
    p.background(100);
    p.fill(0);
    p.rect(200,200,50,50);
  };

  p.keyPressed = function() {
    console.log("keyPressed sketch2");
  }

  p.mouseClicked = function() {
    console.log("mouseClicked sketch2");
  }
};

// this one gets keyPressed and mouseClicked events
var s1 = new p5(sketch1);

// this one just gets mousClicked events
var s2 = new p5(sketch2);

Thanks

lmccart commented 8 years ago

keyPressed is a global event, even when you are in instance mode. it will fire anytime a key is pressed, so if you try to attach more than one keyPressed event, they may not both be fired.

good-grief commented 8 years ago

Thanks. I found a way to deal with it.

lbineau commented 8 years ago

@good-grief Can you explain your workaround ? I have a problem with that too. Even if I don't use keyPressed in one sketch but I instanciate multiple sketches the function does work.

adalberth commented 8 years ago

You could create a normal event.

// es6
document.addEventListener('keydown', e => {
  if (e.keyCode == '37') {
    // Something
  }
});
spoonmanchen commented 6 years ago

Thanks a lot @alexdean .