Actionscript 3 - make sound only play once when objects touch
I have a griddle_mc, bacon_mc, and BaconCooking.wav. I want to play the wav when the bacon is moved onto the griddle. If I move the bacon until it just touches the griddle the wav plays fine, but if I continue to drag the bacon_mc across the griddle the wav becomes loud and distorted, almost like it's playing multiple instances of the wav at th开发者_JAVA百科e same time.
private function __handleSliceDown($evt:MouseEvent):void {
slice1_mc.startDrag(true);
}
private function __handleSliceUp($evt:MouseEvent):void {
slice1_mc.stopDrag();
addEventListener(Event.ENTER_FRAME, __checkHit);
}
private function __checkHit($evt:Event):void {
if (this.slice1_mc.hitTestObject(griddle_mc)) {
if (!hitting) {
sc = BaconCooking.play();
}
}
}
How can I get the wav to play correctly?
EDIT:
private function __checkHit($evt:Event):void {
if (this.slice1_mc.hitTestObject(griddle_mc)) {
if(isPlaying){
sc = BaconCooking.play();
isPlaying = true;
}
}else{
isPlaying = false;
sc.stop();
}
}
- isPlaying is a boolean set to false by default.
Now you have if(isPlaying){
but shouldn't that be if(!isPlaying){
?
The way I would do it: when the two objects hittest, set the isPlaying boolean to true if it was false and play the sound. The isPlaying boolean can only become false again if the objects don't collide anymore.
edit: Since isPlaying is false by default, than it will never play the sound to begin with. your if statement should be:
if(!isPlaying){
<code to play sound
}
Also, I touched in this before, but I will expand: you need an additional event listener that detects when the objects are -not- touching, when that is called you would set isPlaying to false. It has been some time since I've programmed in Actionscript, but that is the general idea of what you need to do.
Use a variable and a conditional statement. Every time the objects collide, it would check if this variable was true. If it was, than it would play the sound and set the variable to true, otherwise, it would do nothing. When the objects were no longer touching, than the variable would be set to false.
精彩评论