从 class (p5.js) 内部切换按钮状态

Toggle button state from inside a class (p5.js)

我需要构建自己的 switch/button,它具有打开或关闭状态,我希望将它作为一个对象,这样我就可以制作很多。但是 draw() / 常量循环使得设置状态变得困难。我做错了什么?

let s;
    
function setup() {
  createCanvas(400, 400);
  background('gray');
  
  s = new Switch(100,100);  
}

function draw() {
  s.draw();
}


function mousePressed(status) {
    if (status === false) { 
      return true;
    } else if (status === true) {
      return false;
    }  
}

class Switch {
  constructor(x,y) {
    this.status = true;
    this.statusColour = 'black';
    this.pos = createVector(x,y);
    this.size = 100;
  }
  
  intersect() {
    if ((mouseX >= this.pos.x && mouseX <= this.pos.x+this.size) && (mouseY >= this.pos.y && mouseY <= this.pos.y+this.size)) {
      return true;
    }
  }
  
  draw() {
    noStroke();
    fill(this.statusColour);
    rect(this.pos.x,this.pos.y,this.size,this.size);
    
    // Action to make switch
    this.intersect() ? this.status = mousePressed(this.status) : null;
    
    
    this.status === true ? this.statusColour = 'green' : this.statusColour = 'black';
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>

你做错了。 mousePressed() 是一个事件回调。它由系统调用。永远不要直接调用它。当鼠标按下时,事件回调函数mousPressed()被调用

在 class Switch 中添加一个方法来翻转按钮:

class Switch {
    // [...]

    switchState() {
        if (this.intersect()) {
            this.status = !this.status;
            this.statusColour = this.status ? 'black' : 'green';
        }
    }

    // [...]
}

将鼠标回调委托给此方法:

function mousePressed(status) {
    s.switchState();
}

看例子:

let s;

function setup() {
    createCanvas(400, 400);
    background('gray');

    s = new Switch(100,100);  
}

function draw() {
    s.draw();
}

function mousePressed(status) {
    s.switchState();
}

class Switch {
    constructor(x,y) {
      this.status = true;
      this.statusColour = 'black';
      this.pos = createVector(x,y);
      this.size = 100;
    }

    intersect() {
        return mouseX >= this.pos.x && mouseX <= this.pos.x+this.size && mouseY >= this.pos.y && mouseY <= this.pos.y+this.size;
    }

    switchState() {
        if (this.intersect()) {
            this.status = !this.status;
            this.statusColour = this.status ? 'black' : 'green';
        }
    }

    draw() {
        noStroke();
        fill(this.statusColour);
        rect(this.pos.x,this.pos.y,this.size,this.size);
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>