0
我的目标是让风暴骑士img在屏幕周围弹跳,并在点击后发出声音。我已经设法实现了,但现在我想添加更多的音效(可能还有两个)。我希望声音效果也是随机的。我尝试了一个数组,但我似乎无法弄清楚。p5.js中的声音效果阵列
var img;
var trooper;
var soundFx;
function preload() {
img = loadImage("stormy3.png");
sfx1 = loadSound('Followme(1).mp3');
sfx2 = loadSound('LetmeseeyourID.mp3');
}
function setup() {
soundFormats('mp3');
soundFx = sfx1;
// background(255, 0, 0, 0.4);
background(0);
var myCanvas = createCanvas(800, 800);
myCanvas.position(0, 0);
trooper = new storm(random(width),random(height));
}
function draw() {
// clear();
background(0);
trooper.show();
trooper.update();
}
function mousePressed() {
trooper.clicked();
}
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.update = function() {
this.x = this.x + this.xSpeed;
this.y = this.y + this.ySpeed;
if(this.x > width || this.x < 0) {
this.xSpeed = this.xSpeed * -1;
}
if(this.y > height || this.y < 0) {
this.ySpeed = this.ySpeed * -1;
}
};
this.clicked = function() {
var d = dist(mouseX,mouseY,this.x,this.y);
if (d < 150) {
this.xSpeed = -5
this.ySpeed = -5;
soundFx.play();
}
};
}
如果你给一个数组,它返回一个随机元素,所以你不需要了'randomSFX'变量的随机函数。它就像'random(soundFx).play();'一样简单 – Pepe