2017-03-20 115 views
0

我试图让我的stormTrooper图像在点击时产生声音效果 - 目前我没有运气...我检查了p5.js网站 - 但不能想办法。对物体的声音效果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(); 
    } 
} 

回答

1

你不会移动小品级mousePressed()功能是Storm对象内(对象应该有一个大写字母BTW开始)。相反,您只需从草图级mousePressed()函数调用Storm对象内的另一个函数即可。

另外请注意,您Storm类不包含功能,所以你当前的代码将无法正常工作。

下面是你需要做的骨架:

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。看起来你对一些不同的事情感到困惑,所以你应该在他们自己的问题中问他们每个人,他们自己的MCVE只是隔离那一步。

例如,您可以创建一个只播放声音的小示例草图吗?完美地工作,无需担心物体或碰撞检测或其他任何事情。除此之外,您是否可以创建一个仅处理碰撞检测的示例程序,比如说,只要鼠标在里面,就改变矩形的颜色?另外,你可以创建一个示例程序来设置对象吗?在开始考虑将它们合并成一个程序之前,让每个人都自己完美地工作。然后,如果您遇到特定的问题,可以将MCVE与特定问题一起发布,我们将从此处开始。祝你好运。

+0

非常感谢您的建议,非常感谢! –