1

I am trying to make a function inside my class, where by pressing the ArrowUp key, it will become true. However, it just says: "Cannot read property 'key' of undefined?

class Boks{
  constructor(x,y,w,h,r,k){
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.r = r;
    this.k = k;
  }

  visSnake(){
    rect(this.x,this.y,this.w,this.h)
  }

  moveSnake(){
    this.x = this.x + speed;
  }

  keyb(event){
    if(event.key === "ArrowUp"){
      return true;
    }
  }
}

My guess is that I have to define some sort of DOM event key in the constructor or parameter to the constructor, but i dont know how?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Mr.Ulis
  • 157
  • 6
  • 1
    How does `keyb()` get called? – takendarkk Sep 20 '19 at 21:11
  • 2
    In [*p5.js*](https://p5js.org/reference/) you've just to define the function [`keyPressed()`](https://p5js.org/reference/#/p5/keyPressed). You don't need to define any DOM event, p5.js does the job for you, you've just to "use" the existing callbacks, which are well documented – Rabbid76 Sep 20 '19 at 21:12
  • could you also paste the html – Aziz.G Sep 20 '19 at 21:17

1 Answers1

3

In p5.js you've just to define the function keyPressed() which is automatically called, if an button is pressed. You don't need to define any DOM event, p5.js does the job for you, you've just to "use" the existing callbacks, which are well documented.
I recommend to read p5.js - Get Started.

If you want to evaluate if the UP key is pressed, then you can evaluate the state of the built in variable keyIsPressed and keyCode in draw:

function draw() {

    if (keyIsPressed && keyCode === UP_ARROW) {
        // [...]
    }

    // [...]
}

See the short example:

let x=0, y=0, w=20, h=20;

function setup(){
    createCanvas(window.innerWidth-20,window.innerHeight-20)
    x = width/2;
    y = height/2;
    frameRate(10);
}

function draw(){
    
    if (keyIsPressed && keyCode === LEFT_ARROW){
        if (x > 0) { 
            x -= w;
        }
    }
    if (keyIsPressed && keyCode === RIGHT_ARROW){
        if (x < width-w) { 
            x += w;
        }
    }   
    if (keyIsPressed && keyCode === UP_ARROW) {
        if (y > 0) { 
            y -= h;
        }
    }
    if (keyIsPressed && keyCode === DOWN_ARROW){
        if (y < height-h) { 
            y += h; 
        }
    }

    background(0);
    stroke(255);
    fill(255);
    rect(x, y, w, h);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
Rabbid76
  • 202,892
  • 27
  • 131
  • 174