物体的音效 p5.js

Sound effect on objects p5.js

我正在尝试让我的 stormTrooper 图像在单击时产生声音效果 - 到目前为止我运气不好......我查看了 p5.js 网站 - 但无法弄清楚.

想知道我是否必须在 storm 对象中包含 mousePressed 函数?

var img;
var trooper;
var sound;

function preload() {

  img = loadImage("stormy3.png");
  sound = loadSound("sounds/Followme.mp3");

}

function setup() {
   // background(255, 0, 0, 0.4);
  background(255, 0, 0, 0.4);
  var myCanvas = createCanvas(windowWidth,windowHeight);
  myCanvas.parent('myContainer');
  myCanvas.position(0, 0);
  trooper = new storm(300,400);
}

function draw() {
 clear();
 trooper.show();
 trooper.movement();
 trooper.bounce();
}

function storm(x,y) {
 this.x = x;
 this.y = y;
 this.xSpeed = 3;
 this.ySpeed = 3;
 this.img = img;

 this.show = function() {
  image(img,this.x,this.y);
};

 this.movement = function() {
   this.x = this.x + this.xSpeed;
   this.y = this.y + this.ySpeed;
};

this.bounce = function() {
  if(this.x > width || this.x < 0) {
    this.xSpeed = this.xSpeed * -1;
}
if(this.y > height || this.y < 0) {
  this.ySpeed = this.ySpeed * -1;
}
};
}

function mousePressed() {

   if (trooper.contains(trooper.x, trooper.y)) {
     sound.play();
   }
}

您不会将草图级 mousePressed() 函数移动到 Storm 对象内部(顺便说一句,对象应该以大写字母开头)。相反,您只需从草图级 mousePressed() 函数调用 Storm 对象内的另一个函数。

另请注意,您的 Storm class 不包含 contains() 函数,因此您当前的代码将无法运行。

这是您需要做的事情的概要:

function Storm(x, y){
   //other variables and functions here

   this.contains = function(x, y){
      //return true if x,y is inside this Storm's hitbox
   }
}

function mousePressed(){
   if(trooper.contains(someX, someY)){
      //play your sound or do whatever you want
   }
}

您还需要启动 breaking your problem down into smaller steps. It looks like you're confused about a few different things, so you should ask about each of them in their own question, with their own MCVE 以隔离该步骤。

例如,您可以创建一个只播放声音的小示例草图吗?让它完美地工作,而不用担心物体或碰撞检测或其他任何事情。除此之外,您能否创建一个仅处理碰撞检测的示例程序,比如只要鼠标在其中就改变矩形的颜色?除此之外,您可以创建一个设置对象的示例程序吗?在您开始考虑将它们组合成一个程序之前,先让它们各自完美地工作。然后,如果您在某个特定步骤遇到困难,您可以 post 一个 MCVE 以及一个特定问题,我们将从那里开始。祝你好运。