我的目标是让一个风暴骑兵img在屏幕周围弹跳,并在点击后发出声音。我已经设法实现了这一点,但现在我想添加更多的声音效果(可能还有两个)。我希望声音效果随机化。我试过一个阵列,但我似乎无法弄明白。
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();
}
};
}
答案 0 :(得分:0)
在这里,您将如何实现这一目标......
Math#random
或 p5#random
生成随机数(索引)并传递该数字播放音效时(索引)至soundFx
var img;
var trooper;
var soundFx;
var randomSFX;
function preload() {
img = loadImage("https://i.imgur.com/aKtmInB.png");
sfx1 = loadSound('https://istack.000webhostapp.com/bell1.mp3');
sfx2 = loadSound('https://istack.000webhostapp.com/bell2.mp3');
}
function setup() {
soundFormats('mp3');
soundFx = [sfx1, sfx2];
// background(255, 0, 0, 0.4);
var myCanvas = createCanvas(635, 218);
myCanvas.position(0, 0);
background(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;
randomSFX = Math.floor(Math.random() * soundFx.length); //or use, floor(random(0, soundFx.length));
soundFx[randomSFX].play();
}
};
}
&#13;
body {
margin: none;
overflow: hidden;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.8/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.8/addons/p5.dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.8/addons/p5.sound.min.js"></script>
&#13;