AS3 hitTestObject not working at all - actionscript-3

I've been working on a large project in Flash CS6 and ActionScript 3 which includes jigsaws etc. I have been using hitTestObject throughout the project and it had been working fine, then all of a sudden it stopped working. It won't work in any new instances or even where it worked before. I created a small test piece, and this isn't working either:
import flash.events.MouseEvent;
hit_txt.visible = false;
object2_mc.addEventListener(MouseEvent.MOUSE_DOWN, drag);
function drag(e:MouseEvent = null):void {
object2_mc.startDrag();
}
if (object2_mc.hitTestObject(object1_mc)) {
hit_txt.visible = true;
}
Any help or suggestions would be greatly appreciated, thanks in advance.

You are not stating when to do the checking of the hit test. So either you check by enter frame, or while you move the object
object2_mc.addEventListener(MouseEvent.MOUSE_MOVE, move);
function move(e:MouseEvent = null):void
{
if (object2_mc.hitTestObject(object1_mc))
{
hit_txt.visible = true;
}
}

Related

Adobe Flash/ActionScript 3.0 moving to next scene but nothing plays

I've searched endlessly for an answer but can't seem to find one.
I'm building a flash presentation for a client. It's got about 15 scenes, the .fla file is 200MB before publishing (26MB afterward). It's a pretty simple operation; I'have a pause/play & replay button, and once the scene is completed a next & replay button appears in the center of the stage.
My issue is when I get to about the 8th scene, halfway through. All my tweens and buttons stop working. Simple fade-in text doesn't come up and my pause/play & replay no longer function. I've tried shifting around scenes to see if it was anything in particular, but no matter what order and what scenes it always stops halfway through the 8th. I don't get any error notifications before, after or during the play. Tracing tells me that the button has been clicked and it's moved to the next scene but it simply will not play. Adding a play(); comment at the first frame of the next scene has not helped either.
Here are my functions that are on Scene 1 Frame 1
function pause_movie(event:MouseEvent):void {
stop();
playBtn.visible = true;
pauseBtn.visible = false;
}
function play_movie(event:MouseEvent):void {
play();
playBtn.visible = false;
pauseBtn.visible = true;
}
function replay_movie(event:MouseEvent):void {
gotoAndPlay(1);
}
function next_movie(event:MouseEvent):void {
this.nextScene();
trace("next_movie " + this.currentScene.name);
}
And then I just add event listeners when my buttons appear per scene
import flash.events.MouseEvent;
//Hide play button to start
playBtn.enabled = true;
pauseBtn.enabled = true;
playBtn.visible = false;
pauseBtn.addEventListener(MouseEvent.CLICK, pause_movie);
playBtn.addEventListener(MouseEvent.CLICK, play_movie);
replayBtn.addEventListener(MouseEvent.CLICK, replay_movie);
Any help is appreciated! Thank you!
I've created a new flash file with a blank canvas (just page number and next button). I'm loading the audio externally now as per #VC.One 's comment and the program stops working at the same scene regardless of which audio file I put in there.
Here is my updated code:
import flash.events.Event;
import flash.media.Sound;
import flash.net.URLRequest;
import flash.media.SoundChannel;
var channel:SoundChannel = new SoundChannel;
var s:Sound = new Sound();
function newSound() {
s.removeEventListener(Event.COMPLETE, onSoundLoaded);
s = new Sound();
s.addEventListener(Event.COMPLETE, onSoundLoaded);
}
function onSoundLoaded(e:Event):void
{
channel = s.play();
}
function next_movie(event:MouseEvent):void
{
channel.stop();
try {
s.close();
}
catch(e:Error) {
trace("File already loaded");
}
this.nextScene();
trace("next_movie " + this.currentScene.name);
}
and each scene starts with:
pageNum.text = this.currentScene.name;
skipBtn.addEventListener(MouseEvent.CLICK, next_movie);
newSound();
s.load(new URLRequest('audio/ISB page 17 tk 1.mp3'));
Finally solved this issue. The scenes added together were more than the 16k frames Flash is apparently limited to. I had to convert each scene into a movieclip and put them in each of their own frame all in one scene with a bit of coding to play each one after the previous one finished. Everything works fine now. Thanks guys!

Problems with an object appearing on a frame I don't want it to appear on AS3

I am a total noob at AS3, roughly 1 year experience so please be lenient with me :)
I currently am making an endless runner game and I'm making the obstacles spawn using this method
var therespawn:RespawnObject;
var thecone:trafficcone;
var started:Boolean = false;
var dx:Number = 10;
var dy:Number = 10;
stage.addEventListener(Event.ENTER_FRAME, startGame);
addEventListener(Event.ENTER_FRAME, collision);
addEventListener(Event.ENTER_FRAME, coneCollision);
function startGame(evt:Event):void {
if (started == false) {
spawnHazard();
}
}
function spawnHazard() {
started = true;
therespawn = new RespawnObject();
addChild(therespawn);
thecone = new trafficcone();
addChild(thecone);
therespawn.x = -50;
therespawn.y = 310;
thecone.x = 600;
thecone.y = 310;
}
function collision(evt:Event):void {
thecone.x -= 15;
if(thecone.hitTestObject(therespawn)) {
thecone.x = 600;
}
}
Now the only way to finish the game or end it is to get hit by an obstacle which ive shown down below:
function coneCollision(evt:Event):void {
if(MainChar.hitTestObject(thecone)) {
gotoAndStop("frameFive");
}
}
Everytime the highscore frame appears the cone is still spawning and despawning, why is that?
I haven't declared them as global?
Any help appreciated, thanks!
You can fix your problem by setting started to false:
function coneCollision(evt:Event):void {
if(MainChar.hitTestObject(thecone)) {
started = false;
gotoAndStop("frameFive");
}
}
The flash timeline really only has to with the way MovieClips are visually displayed as children of the stage. Removing an object from the timeline doesn't just suddenly nullify all the code associated with that object. In other words, your ENTER_FRAME method still runs in the background even if the object is no longer a child of the Stage, regardless of the frame number for the MovieClip. If you're serious about coding you might consider investigating in Classes and Object Oriented AS3. Classes are much nicer to work with than the Flash timeline.

Sound won't stop when I go back to a previous Stage with code

i have 4 scenes and i put my script for music in scene 2 and then i jump to scene 3 but when i go back to scene 2 and press pause or stop, my music wont do that, but when i play, the music play and i get 2 music start :(, can anybody help the script ?
regards im newbie,
stop();
import flash.events.MouseEvent;
import flash.media.SoundChannel;
//declaring all variables
var isPlaying:Boolean = false;// boolean type of variables can be true or false only
var myMusic = new soothing();// saving music in a varaible
var myChannel:SoundChannel = new SoundChannel();// sound channel Class to stop
var lastPosition:Number = 0;
play_btn.addEventListener(MouseEvent.CLICK, onPlayClick);
pause_btn.addEventListener(MouseEvent.CLICK, onPauseClick);
stop_btn.addEventListener(MouseEvent.CLICK, onStopClick);
function onPlayClick(event:MouseEvent):void
{
if (isPlaying == false)
{
isPlaying = true;
myChannel = myMusic.play(lastPosition);
}
myChannel.addEventListener(Event.SOUND_COMPLETE, completeHANDLER);
function completeHANDLER(event:Event):void
{
lastPosition = 0;
isPlaying = false;
}
}
function onPauseClick(event:MouseEvent):void
{
isPlaying = false;
lastPosition = myChannel.position;
myChannel.stop();
}
function onStopClick(event:MouseEvent):void
{
if (isPlaying == true)
{
isPlaying = false;
lastPosition = 0;
myChannel.stop();
}
}
homebtn.addEventListener(MouseEvent.CLICK, qnextScene);
function qnextScene(event:MouseEvent):void
{
gotoAndStop(1, "Scene 2");
}
gallerybtn.addEventListener(MouseEvent.CLICK, nxtScene);
function nxtScene(event:MouseEvent):void
{
gotoAndStop(1, "Scene 3");
}
mebtn.addEventListener(MouseEvent.CLICK, nextsScene);
function nextsScene(event:MouseEvent):void
{
gotoAndStop(1, "Scene 4");
}
Ahhh, yes, the infamous stage sound bug I spent four months chasing down.
One fix: DON'T GO BACKWARDS ON STAGES. They're quite buggy.
Instead, what you put on a given stage, instead put inside a MovieClip. Create two functions instead each of those major MovieClips, one to start all the sounds, animations, etc that need to happen when it appears. The other to STOP sounds, animations, etc.
Then, set up a SINGLE stage with code to swap between these.
One other issue you're going to run into when you start in on this approach is that variables will seemingly clear themselves spontaneously. This is due to the nature of the timeline.These master movieclips should have ONE FRAME ONLY, and stop(); must be the first line of code after the import. If you have multiple frames on these master movieclips, or if you neglect stop, things will keep re-initializing, which is a pain in the butt.
(Heading this off at the pass: yes, code on the timeline is
acceptable, as long as all the code relates directly to the object it
is on the timeline OF. Pure code should be parked in the document
class and linked classes. The idea that you should never put code on
the timeline is a relic practice from AS2.)

How to stop sound in the middle of playing

I'm trying to write a bit of code that plays a sound while a buttons pressed however if the button has been pressed and the sound is playing then the sound is paused and played again rather then just playing and overlapping.
this is what I have
var sound:alarm = new alarm();
var isPlaying:Boolean = false;
public function Main()
{
button.addEventListener(MouseEvent.CLICK,playSound);
}
public function playSound(e:Event):void
{
if(isPlaying)sound.stop();
sound.play();
isPlaying=true;
}
at first glance It seemed to have worked but then I saw the following in my output
TypeError: Error #1006: stop is not a function.
at Main/playSound()
TypeError: Error #1006: stop is not a function.
at Main/playSound()
so apparently it works although stop is not a method of the Sound class. what would be the proper way of implementing this? Also I've been wondering if there is a more proper condition I can use, because with this code sound.stop() is called every time the function is entered after the first button click, is there a method that allows me to check in real time whether or not a sound is playing?
In your code, the function playSound(e:Event) should be playSound(e:MouseEvent);Also your right stop() is not a method of the Sound class, however your not using the Sound class, your using the alarm class (unless the alarm class extends the Sound class).On another note, I searched google and this popped up, Flash Play/Pause Sound
Update:
import flash.media.SoundChannel;
// Make sure to import the SoundChannel class
var sc:SoundChannel = new SoundChannel();
var sound:Sound = new alarm();
var isPlaying:Boolean = false;
var pausePos:Number = 0;
public function Main()
{
button.addEventListener(MouseEvent.CLICK,playSound);
}
public function playSound(e:MouseEvent):void
{
if(isPlaying) {
pausePos = sc.position;
sc.stop();
isPlaying = false;
} else {
sc = sound.play(pausePos);
isPlaying = true;
}
}
This code should work, however I have not tested it so if any errors are given or the desired result is not met just let me know and I'll see what I can do.
Short answer...okay, entire answer from me :). Instead of using the sound object, try the SoundChannel object. It offers more options, including volume and balance control, and most prominently, stop.
Documentation should provide enough info for using it. It's relatively common.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/SoundChannel.html

Controlling FPS of a loaded swf

I'm working on a flash app where I load multiple swf's. But the problem is that they have different framerates (12/25/30). If I add 2 swf's they both play at 25fps. I found numerous topic about this but I can't get it to work (in AS3). Does anyone know why it doesn't work and how to make it working?
public class MainClass extends MovieClip
{
var loader:Loader = new Loader();
var request:URLRequest;
var mcMedia:MovieClip = new MovieClip();
MovieClip.prototype.setFrameRate = function(frameRate:Number)
{
var mc:MovieClip = this;
if (mc.tweenFaster != null)
{
Timer(mc.tweenFaster).stop();
}
mc.tweenFaster = new Timer(1000/frameRate);
mc.tweenFaster.addEventListener(TimerEvent.TIMER, timelineFaster);
mc.tweenFaster.start();
function timelineFaster(event:TimerEvent = null)
{
if (mc.currentFrame == mc.totalFrames)
{
mc.tweenFaster.stop();
mc.gotoAndStop(1);
}
else
{
trace(mc.currentFrame);
mc.nextFrame();
}
event.updateAfterEvent();
}
}
public function MainClass()
{
configureListeners();
request = new URLRequest("data/7/7.swf");
try
{
loader.load(request);
}
catch (error:Error)
{
trace("Unable to load requested document.");
}
}
private function configureListeners():void
{
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.contentLoaderInfo.addEventListener(Event.OPEN, openHandler);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
loader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
private function completeHandler(event:Event):void
{
loader.content.scaleX = 550/event.target.width;
loader.content.scaleY = 400/event.target.height;
mcMedia.addChild(loader);
mcMedia.setFrameRate(12);
addChild(mcMedia);
}
In as3, if you're just looking to change the framerate, use stage.frameRate = 12; or whatever;
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/Stage.html#frameRate
In AS3, while you can use prototypes, you generally don't. I'd rewrite your setFrameRate function (which is badly named, shouldn't it be more.. tweenFaster, or matchFrameRate or something?)
I'd make a helper function like this:
package util{
//imports
public class TweenFasterMC extends MovieClip{
public var mc:MovieClip;
public function matchFrameRate(frameRate:Number):void
{
if (tweenFaster != null)
{
Timer(mc.tweenFaster).stop();
}
tweenFaster = new Timer(1000/frameRate);
tweenFaster.addEventListener(TimerEvent.TIMER, timelineFaster);
tweenFaster.start();
}
function timelineFaster(event:TimerEvent = null):void
{
if (currentFrame == totalFrames)
{
tweenFaster.stop();
gotoAndStop(1);
}
else
{
trace(currentFrame);
nextFrame();
}
event.updateAfterEvent();
}
}
Also, clean up your event listeners, that strong timer event listener will cause a lot of problems if you have a lot of mc's your applying this functionality to.
As far as I know all MovieClips in one flash player instance (sharing the same 'stage') will run at the same speed - there is no way to have two clips running at different speeds. So to adjust the speed you have to resort to calling gotoAndStop() on all MovieClips in the loaded clip at the right time - that won't be fun.
Code along the lines that quoo is showing will only work if the loaded swf contains just 1 MovieClip (no nesting) as far as I can see.
It seems to me that the most likely reason why this wouldn't work is that it requires every clip you load to be a simple, completely non-dynamic animation that loops for ever. If the loaded content is that simple, why not just adjust it to look better at 30fps? (If it's extremely long, a JSFL script could automate the process of adding extra frames.) Alternately, if the content isn't that simple, then attempting to change its timing by calling nextFrame from elsewhere is not going to give you what you want.
With all that said, if you're sure this is what you want to do but you're getting 0 as a return for currentFrame in your loaded content, are you sure they are AS3 SWFs? If they aren't, AS3/AS2 interoperation is a hairy subject that will warrant reading up on.
This is a real hassle, I've been scouring the net for an answer. I have particles following a path, and I want to change the speed that these particles follow the path dynamically, without changing the whole movie. just the particles movie clip.
I've tried greensock, but, that doesn't really work like i need.. i'd think there would be something that you can change dynamically for each mc, but, no dice.
the stage.frameset is only for the whole movie... argggggggg..... sucks..