2017-03-20 15 views
0

クリックしたときに効果音を出すためにstormTrooperイメージを取得しようとしています - これまでの運がない... p5.jsのウェブサイトをチェックしましたが、それを理解する。オブジェクトへのサウンドエフェクトp5.js

嵐のオブジェクトの中に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

あなたは(オブジェクトがところで大文字で始まるべきである)Stormオブジェクト内であることがスケッチレベルmousePressed()機能を移動しないであろう。代わりに、スケッチレベル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というステップを分離してください。

たとえば、音だけを再生する小さなサンプルスケッチを作成できますか?オブジェクトや衝突検出など何も心配することなく、完全に動作させることができます。これとは別に、マウスがその中にあるときはいつでも矩形の色を変えるなど、衝突検出を処理するサンプルプログラムを作成できますか?これとは別に、オブジェクトを設定するサンプルプログラムを作成できますか? 1つのプログラムにそれらを組み合わせることを考え始める前に、それらのそれぞれが完全に機能するようにしてください。その後、特定のステップで立ち往生すると、特定の質問とともにMCVEを投稿することができます。そこで私たちはそこから行くつもりです。がんばろう。

+0

あなたのアドバイスをいただき、ありがとうございました。 –

関連する問題