How to smoothly scroll content in an AIR Android Application? - actionscript-3

I have written a small class to be used to scroll content on mobile devices. The class works fine but the scrolling doesn't feel smooth. Here is the class:
package {
import flash.display.Sprite;
import flash.display.InteractiveObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.InteractiveObject;
import flash.geom.Rectangle;
import com.greensock.TweenMax;
import com.greensock.easing.*;
import flash.utils.setTimeout;
public class FlickScroll extends Sprite {
private var currentY:Number;
private var lastY:Number;
private var vy:Number;
public var clickable:Boolean = true;
private var dragging:Boolean = false;
private var firstY:Number;
private var secondY:Number;
private var content:InteractiveObject;
private var masker:InteractiveObject;
private var topBounds:Number;
private var bottomBounds:Number;
private var Offset:Number;
public var friction:Number = .90;
public var flickable:Boolean = false;
public var scrollVelocity:Number;
public function FlickScroll(Masker:InteractiveObject, Content:InteractiveObject, TopBounds:Number, BottomBounds:Number) {
masker = Masker;
content = Content;
topBounds = TopBounds;
bottomBounds = BottomBounds;
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true);
}
private function onAddedToStage(evt:Event):void
{
init();
this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
addEventListener(Event.ENTER_FRAME, onLoop, false, 0, true);
content.mask = masker;
content.cacheAsBitmap = true;
}
private function init():void
{
currentY = content.y;
lastY = content.y;
vy = 0;
scrollVelocity = 2;
content.addEventListener(MouseEvent.MOUSE_DOWN, onContentDown, false, 0, true);
}
private function onContentDown(evt:MouseEvent):void
{
firstY = content.y;
Offset = content.mouseY;
trace(mouseY, Offset, mouseY - Offset);
content.addEventListener(MouseEvent.MOUSE_MOVE, onContentMove, false, 0, true);
stage.addEventListener(MouseEvent.MOUSE_UP, onContentUp, false, 0, true);
}
private function onContentMove(evt:MouseEvent):void
{
dragging = true;
clickable = false;
content.y = mouseY - Offset;
if(content.y > topBounds + 200)
{
content.y = topBounds + 200;
}
else if(content.y < bottomBounds - 200)
{
content.y = bottomBounds - 200;
}
trace("ContentY: ", content.y, "Bottom Bounds: ", bottomBounds, "Top Bounds: ", topBounds);
evt.updateAfterEvent();
}
private function onContentUp(evt:MouseEvent):void
{
secondY = content.y;
var dy:Number = secondY - firstY;
if(dy < 20 && dy > -20)
{
clickable = true;
}
if(content.y > this.topBounds)
{
TweenMax.to(content, .4, {y:topBounds, ease:Expo.easeOut});
}
else if( content.y < this.bottomBounds)
{
TweenMax.to(content, .4, {y:bottomBounds, ease:Expo.easeOut});
}
else
{
dragging = false;
}
//setTimeout(setDraggingFalse, 400);
content.removeEventListener(MouseEvent.MOUSE_MOVE, onContentMove);
content.removeEventListener(MouseEvent.MOUSE_UP, onContentUp);
}
private function onLoop(evt:Event):void
{
if(this.flickable)
{
if(dragging)
{
lastY = currentY;
currentY = mouseY;
vy = (currentY - lastY)/scrollVelocity;
}
else
{
content.y += vy;
vy *= friction;
}
}
if(!dragging)
{
if(content.y > topBounds)
{
content.y = topBounds;
}
else if(content.y < bottomBounds)
{
content.y = bottomBounds;
}
}
}
public function updateBounds(top:Number, bottom:Number):void
{
bottomBounds = bottom;
topBounds = top;
}
private function setDraggingFalse():void
{
dragging = false;
}
}
}
Sorry for the code being really messy.
What steps can I take to make the scrolling feel more smooth? Any help is greatly appreciated.

If youre using bitmaps, try following this guide. It deals with smoothly scrolling with bitmaps.
If youre dealing with a movieclip, startDrag() and stopDrag() aren't too bad. Maybe adding a Tween and decelerating it based on a frame by frame comparison of the mouses last y and current y to get the "thrust" on release of the mouse. Might have to lock the x position of the movieclip on a mouse move event (or y depending how how you want it to scroll).

Related

AS3 Frogger Pixel Perfect Collision

I have created a simple AS3 frogger game and used .hitTestObject to test if the frog hits any of the obstacles. This is not effective as the frog hits objects that aren't touching it at all. I am new to AS3 and have no idea where to start with coding for this. Any help would be appreciated!
package {
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.ui.*;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.utils.Timer;
import flash.display.BitmapData;
import flash.display.Bitmap;
public class Main extends MovieClip
{
//set variables
public var frog_spriteInstance:frog_sprite;
public var safeZoneInstance1 : safeZone;
public var safeZoneInstance2: safeZone;
public var safeZoneInstance3 : safeZone;
public var whitecar : car1;
public var whitecar1 : car1;
public var whitecar2 : car1;
public var truck1 : truck_sprite;
public var truck2: truck_sprite;
public var redcar : car_sprite;
public var redcar2 : car_sprite;
public var redcar3 : car_sprite;
public var log1 : log_sprite;
public var log2 : log_sprite;
public var log3 : log_sprite;
public var letters : Letters;
public var letters2 : Letters_2;
public var letters3 : Letters_3;
public var letters4 : Letters_4;
public var health : HealthBar;
public var firstletter : firstLetter;
public var secondletter : secondLetter;
public var thirdletter : thirdLetter;
public var fourthletter : fourthLetter;
var mysound:Sound = new (mySound);
public function Main()
{
// constructor code
safeZoneInstance1 = new safeZone();
stage.addChild(safeZoneInstance1);
safeZoneInstance1.x = 300;
safeZoneInstance1.y=545
safeZoneInstance2 = new safeZone();
stage.addChild(safeZoneInstance2);
safeZoneInstance2.x = 300;
safeZoneInstance2.y=300
safeZoneInstance3 = new safeZone();
stage.addChild(safeZoneInstance3);
safeZoneInstance3.x = 300;
safeZoneInstance3.y=100
whitecar = new car1();
stage.addChild(whitecar);
whitecar.x = 300;
whitecar.y = 500
whitecar1 = new car1();
stage.addChild(whitecar1);
whitecar1.x = 550;
whitecar1.y = 480
whitecar2 = new car1();
stage.addChild(whitecar2);
whitecar2.x = 50;
whitecar2.y = 480
truck1 = new truck_sprite();
stage.addChild (truck1);
truck1.x = 1000;
truck1.y = 430
truck2 = new truck_sprite();
stage.addChild (truck2);
truck2.x = 300;
truck2.y = 430
redcar = new car_sprite();
stage.addChild (redcar);
redcar.x = 300;
redcar.y = 340
redcar2 = new car_sprite();
stage.addChild (redcar2);
redcar2.x = 100;
redcar2.y = 375
redcar3 = new car_sprite();
stage.addChild (redcar3);
redcar3.x = 500;
redcar3.y = 375
log1 = new log_sprite();
stage.addChild(log1);
log1.x = 300;
log1.y = 230
log2 = new log_sprite();
stage.addChild(log2);
log2.x = 100;
log2.y = 150
log3 = new log_sprite();
stage.addChild(log3);
log3.x = 500;
log3.y = 150
letters = new Letters();
letters.x = randomRange(100,500) ;
letters.y = randomRange(100,500);
stage.addChild(letters);
letters2 = new Letters_2();
letters2.x = randomRange(100,500) ;
letters2.y = randomRange(100,500);
stage.addChild(letters2);
letters3 = new Letters_3();
letters3.x = randomRange(100,500) ;
letters3.y = randomRange(100,500);
stage.addChild(letters3);
letters4 = new Letters_4();
letters4.x = randomRange(100,500) ;
letters4.y = randomRange(100,500);
stage.addChild(letters4);
frog_spriteInstance = new frog_sprite();
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
health = new HealthBar();
stage.addChild(health);
health.x = 130;
health.y = 20;
health.width = 100;
stage.addEventListener(KeyboardEvent.KEY_DOWN, moveFrog);
stage.addEventListener(Event.ENTER_FRAME, movecars);
stage.addEventListener(Event.ENTER_FRAME, movetrucks);
stage.addEventListener(Event.ENTER_FRAME, moveredcars);
stage.addEventListener(Event.ENTER_FRAME, movelogs);
stage.addEventListener(Event.ENTER_FRAME,checkforcollision);
mysound.play();
}
public function moveFrog(e:KeyboardEvent)
{
// get the key pressed and then move the player
{
if (e.keyCode == Keyboard.UP)
{
frog_spriteInstance.rotation = 0;
frog_spriteInstance.y -= 50;
}
if (e.keyCode == Keyboard.DOWN)
{
frog_spriteInstance.rotation = 180;
frog_spriteInstance.y += 50;
}
if (e.keyCode == Keyboard.LEFT)
{
frog_spriteInstance.rotation = -90;
frog_spriteInstance.x -= 50;
}
if (e.keyCode == Keyboard.RIGHT)
{
frog_spriteInstance.rotation = 90;
frog_spriteInstance.x += 50;
}
}
}
function movecars(event:Event)
{
//move cars across screen and when they disappear, reappear at the other side
whitecar.x -= 3;
if (whitecar.x<-100){
whitecar.x=650;
}
whitecar1.x -= 3;
if (whitecar1.x<-100){
whitecar1.x=650;
}
whitecar2.x -= 3;
if (whitecar2.x<-100){
whitecar2.x=650;
}
}
function movelogs(event:Event)
{
//move logs across screen and when they disappear, reappear at the other side
log1.x -= 5;
if (log1.x<-100){
log1.x=650;
}
log2.x -= 5;
if (log2.x<-100){
log2.x=650;
}
log3.x -= 5;
if (log3.x<-100){
log3.x=650;
}
}
function movetrucks(event:Event)
{
//move trucks across screen and when they disappear, reappear at the other side
truck1.x +=3;
if (truck1.x>650){
truck1.x=-100;
}
truck2.x +=3;
if (truck2.x>650){
truck2.x=-100;
}
}
function moveredcars(event:Event)
{
//move red cars across screen and when they disappear, reappear at the other side
redcar.x +=3;
if (redcar.x>650){
redcar.x=-100;
}
redcar2.x +=3;
if (redcar2.x>650){
redcar2.x=-100;
}
redcar3.x +=3;
if (redcar3.x>650){
redcar3.x=-100;
}
}
function checkforcollision(event:Event)
{
//check for collisions
if (frog_spriteInstance.hitTestObject(log1) || (frog_spriteInstance.hitTestObject(log2) || (frog_spriteInstance.hitTestObject(log3) || (frog_spriteInstance.hitTestObject(whitecar) || (frog_spriteInstance.hitTestObject(whitecar1) || (frog_spriteInstance.hitTestObject(whitecar2) || (frog_spriteInstance.hitTestObject(log2) || (frog_spriteInstance.hitTestObject(truck1) || (frog_spriteInstance.hitTestObject(truck2) || (frog_spriteInstance.hitTestObject(redcar) || (frog_spriteInstance.hitTestObject(redcar2) || (frog_spriteInstance.hitTestObject(redcar3))))))))))))){
//reset frog if hits an obstacle
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
//reduce health bar
health.width -= 10;
}
//remove event listeners when health is empty
if (health.width == 0){
stage.removeEventListener(Event.ENTER_FRAME, movecars);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, moveFrog);
stage.removeEventListener(Event.ENTER_FRAME, movetrucks);
stage.removeEventListener(Event.ENTER_FRAME, moveredcars);
stage.removeEventListener(Event.ENTER_FRAME, movelogs);
}
//add letters to bottom of screen when hit correctly
if (frog_spriteInstance.hitTestObject(letters)){
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
stage.removeChild(letters);
firstletter = new firstLetter();
stage.addChild(firstletter);
firstletter.x=345;
firstletter.y=600;
}
if (frog_spriteInstance.hitTestObject(letters2)){
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
stage.removeChild(letters2);
secondletter = new secondLetter();
stage.addChild(secondletter);
secondletter.x=206;
secondletter.y=600;
}
if (frog_spriteInstance.hitTestObject(letters3)){
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
stage.removeChild(letters3);
thirdletter = new thirdLetter();
stage.addChild(thirdletter);
thirdletter.x=273;
thirdletter.y=600;
}
if (frog_spriteInstance.hitTestObject(letters4)){
stage.addChild(frog_spriteInstance);
frog_spriteInstance.x=300;
frog_spriteInstance.y=550;
stage.removeChild(letters4);
health.width -= 10;
fourthletter = new fourthLetter();
stage.addChild(fourthletter);
fourthletter.x=25;
fourthletter.y=620;
}
}
function randomRange(minNum:Number, maxNum:Number):Number
{
//random generator for letter positioning
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
}
}
Also my code is pretty dodgy so any suggestions on improvement are very welcome.
To perform pixel perfect hit test from two arbitrary display objects you have to draw them to bitmaps and use BitmapData/hitTest().
Here is a generalized function that does this:
function hitTestShapes(object1:DisplayObject, object2:DisplayObject, threshold:uint = 1):Boolean {
var bounds1:Rectangle = object1.getBounds(object1.parent);
var matrix1:Matrix = object1.transform.matrix;
matrix1.tx = object1.x - bounds1.x;
matrix1.ty = object1.y - bounds1.y;
var bmp1:BitmapData = new BitmapData(bounds1.width, bounds1.height, true, 0);
bmp1.draw(object1, matrix1);
var bounds2:Rectangle = object2.getBounds(object2.parent);
var matrix2:Matrix = object2.transform.matrix;
matrix2.tx = object2.x - bounds2.x;
matrix2.ty = object2.y - bounds2.y;
var bmp2:BitmapData = new BitmapData(bounds2.width, bounds2.height, true, 0);
bmp2.draw(object2, matrix2);
return bmp1.hitTest(bounds1.topLeft, threshold, bmp2, bounds2.topLeft, threshold);
}
Note, though, that drawing to bitmaps is rather slow, so be careful not to over-use this kind of function or you will have performance issues. In fact, it would be a good idea to use hitTestObject() first, which is very fast and detects bounding box intersections, then only call hitTestShapes() to refine your check. In other words:
if (frog_spriteInstance.hitTestObject(log1) && hitTestShapes(frog_spriteInstance, log1)) { }
As for suggestions on your code, there's a lot of potential for de-duplicating by way of arrays, loops, and functions. For example, instead of defining all your objects as separate variables, just store them all in an array (or vector):
public var safeZones:Array = [];
public var obstacles:Array = [];
public var letters:Array = [];
To populate the arrays, you can push values into them and use a function to consolidate all your duplicate object setup code:
(Code convention note: use "UpperCamelCase" for class names.)
public function Main(){
addSafeZone(300, 545);
addSafeZone(300, 300);
addSafeZone(300, 100);
addObstacle(WhiteCar, 300, 500);
addObstacle(WhiteCar, 550, 480);
addObstacle(WhiteCar, 50, 480);
addObstacle(Truck, 1000, 430);
addObstacle(Truck, 300, 430);
addObstacle(RedCar, 300, 340);
addObstacle(RedCar, 100, 375);
addObstacle(RedCar, 500, 375);
addObstacle(Log, 300, 230);
addObstacle(Log, 100, 150);
addObstacle(Log, 500, 150);
addRandomLetters(Letters_1);
addRandomLetters(Letters_2);
addRandomLetters(Letters_3);
addRandomLetters(Letters_4);
}
private function addSafeZone(x:Number, y:Number):void {
var safeZone:SafeZone = new SafeZone();
stage.addChild(safeZone);
safeZone.x = x;
safeZone.y = y
safeZones.push(safeZone);
}
private function addObstacle(spriteClass:Class, x:Number, y:Number):void {
var obstacle:Sprite = new spriteClass();
stage.addChild(obstacle);
obstacle.x = x;
obstacle.y = y
obstacles.push(obstacle);
}
private function addRandomLetters(lettersClass:Class):void {
var lettersSprite:Sprite = new lettersClass();
lettersSprite.x = randomRange(100, 500);
lettersSprite.y = randomRange(100, 500);
stage.addChild(lettersSprite);
letters.push(lettersSprite);
}
Now you can loop over the arrays to perform all your actions. For example, to check for a hit against any obstacle:
for each(var obstacle:DisplayObject in obstacles){
if(frog.hitTestObject(obstacle) && hitTestShapes(frog, obstacle)){
// The frog hit an obstacle!
}
}
You could also combine all our "move" functions into one, which moves each obstacle based on their type:
private function moveObstacles(e:Event):void {
for each(var obstacle in obstacles){
if(obstacle is WhiteCar){
obstacle.x -= 3;
}
else if(obstacle is RedCar){
obstacle.x += 3;
}
else if(obstacle is Truck){
obstacle.x += 3;
}
else if(obstacle is Log){
obstacle.x -= 5;
}
if(obstacle.x < -100){
obstacle.x = 650;
}
else if(obstacle.x > 650){
obstacle.x = -100;
}
}
}
Lastly, you really should only need a single ENTER_FRAME handler. Just call whatever functions you want from in there. Adding multiple ENTER_FRAME handlers can get troublesome to manage. For example, just do this:
addEventListener(Event.ENTER_FRAME, update);
private function update(e:Event):void {
moveObstacles();
doOtherStuff();
anythingYouNeedToDo();
}
This way you only need to removeEventListener(Event.ENTER_FRAME, update) to stop the game, not a whole bunch of ENTER_FRAME handlers.
I haven't tested any of this code, but you get the general idea. Let me know if you have any issues with it and I can help.

Action Script 3, how to make characters jump?

I am creating a simple 2D platformer in Flash Develop as3 but I don't know how to create a way for my characters to jump.
Here is my code for main.as:
package
{
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
/**
* ...
* #author Harry
*/
public class Main extends Sprite
{
public var StartButton:Go;
public var FireBoy:Hero;
public var WaterGirl:Female;
public var Door1:Firedoor;
public var Door2:Waterdoor;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
public function init(e:Event = null):void
{
StartButton = new Go();
addChild(StartButton);
StartButton.addEventListener(MouseEvent.CLICK, startgame);
}
private function startgame(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
removeChild(StartButton);
FireBoy = new Hero ();
stage.addChild(FireBoy);
FireBoy.y = 495;
//This allows movement for FireBoy
stage.addEventListener(KeyboardEvent.KEY_DOWN, HandleHeroMove);
WaterGirl = new Female();
stage.addChild(WaterGirl);
WaterGirl.x = 70;
WaterGirl.y = 495;
stage.addEventListener(KeyboardEvent.KEY_DOWN, HandleFemaleMove);
Door1 = new Firedoor();
stage.addChild(Door1);
Door1.x = 5;
Door1.y = 62;
Door2 = new Waterdoor();
stage.addChild(Door2);
Door2.x = 100;
Door2.y = 62;
graphics.beginFill(0x804000, 1);
graphics.drawRect(0, 0, 800, 40);
graphics.endFill();
graphics.beginFill(0x804000, 1);
graphics.drawRect(0, 170, 600, 40);
graphics.endFill();
graphics.beginFill(0x804000, 1);
graphics.moveTo(800, 200);
graphics.lineTo(800, 700);
graphics.lineTo(400, 700);
graphics.lineTo(100, 700);
graphics.endFill();
graphics.beginFill(0x804000, 1);
graphics.drawRect(0, 580, 800, 40);
graphics.endFill();
}
//This handles FireBoys movement
public function HandleHeroMove(e:KeyboardEvent):void
{
trace(e.keyCode);
//This is for moving to the left
if (e.keyCode == 37)
{
FireBoy.x = FireBoy.x - 30;
Check_Border();
}
//This is for moving to the right
else if (e.keyCode == 39)
{
FireBoy.x = FireBoy.x + 30;
Check_Border();
}
else if (e.keyCode == 38)
{
FireBoy.grav = -15;
}
}
//This handles WaterGirls movement
public function HandleFemaleMove (e:KeyboardEvent):void
{
trace(e.keyCode);
//This is for moving to the left
if (e.keyCode == 65)
{
WaterGirl.x = WaterGirl.x - 30;
Check_Border();
}
//This is for moving to the right
else if (e.keyCode == 68)
{
WaterGirl.x = WaterGirl.x + 30;
Check_Border();
}
else if (e.keyCode == 87)
{
WaterGirl.grav = -15;
}
}
//This stops characters from leaving the screen
public function Check_Border():void
{
if (FireBoy.x <= 0)
{
FireBoy.x = 0;
}
else if (FireBoy.x > 750)
{
FireBoy.x = 750;
}
if (WaterGirl.x <= 0)
{
WaterGirl.x = 0;
}
else if (WaterGirl.x > 750)
{
WaterGirl.x = 750;
}
}
}
}
Here is my code for Hero.as (I have identical code for Female.as):
package
{
import flash.display.Bitmap;
import flash.display.Sprite;
/**
* ...
* #author Harry
*/
public class Hero extends Sprite
{
[Embed(source="../assets/FireBoy.jpg")]
private static const HeroFireBoy:Class;
private var FireBoy:Bitmap;
public var grav:int = 0;
public var floor:int = 580;
public function Hero()
{
FireBoy = new Hero.HeroFireBoy();
scaleX = 0.1;
scaleY = 0.1;
addChild(FireBoy);
}
public function adjust():void
{
FireBoy.y += grav;
if(FireBoy.y+FireBoy.height/2<floor)
grav++;
else
{
grav = 0;
FireBoy.y = floor - FireBoy.height / 2;
}
if (FireBoy.x - FireBoy.width / 2 < 0)
FireBoy.x = FireBoy.width / 2;
if (FireBoy.x + FireBoy.width / 2 > 800)
FireBoy.x = 800 - FireBoy.width / 2;
}
}
}
Please can you suggest exactly what code I should write and where to put it because, I can't find anything helpful and i am getting quite stressed over it.
One way to do is like this: in your Hero.as, you functions like jump, move_left and move_right and keep keep the coordinates within the Hero class. Then call those methods wherever you instantiate your Hero object.
As as example in your main.as, you may execute this code when space bar or up-arrow-key is pressed to make your Hero jump:
var hero:Hero = new Hero();
hero.jump();
If it is a simple jump on Y-axis, then you just have to change the Y-axis value. If it is both X-axis and Y-axis, like a forward jump, then you may consider Trigonometry Sine function to calculate the point on which your character should move to make it look smooth.
You don't need identical Female.as class. What you should do is this: Create a class (probably named Character). Add jump, move_left, move_right functions to this class. And then inherit Character class in Hero.as and Female.as. (You need to Google "inheritance" to learn more about this). Then you can instantiate Hero and Female with the same code that resides in Character class.
You may also need to override in Hero.as and Female.as:
[Embed(source="../assets/FireBoy.jpg")]
private static const HeroFireBoy:Class;
in your Hero.as and Female.as, to assign the correct image.

AS3 - how to remove a child when it reaches a certain point, and re add the child

So first off i'd like to state that i am not very good at AS3, i'm completely self taught so i am sure that there are many things i've done badly, inefficiently or plain wrong and i'm happy for any comments on these if there is things i can improve.
In addition, i have done this with classes, however i am now running into a time problem and have decided to make things work first and sort out the class files properly later, i know this is also very bad practice and makes more work than needed, however as i'm not so confident in their use, i would rather complete the work.
So to my question, i am creating a platform game and so far i've got the movement and jumping from platform to platform down, and i am trying to add the scrolling functionality of the game now, the way i am attempting this is by removing a child when it reaches the bottom of the screen, and then adding that child back in a random position.
on the start function i have this array to add the child and randomize it's position:
for(i=0;i<8;i++) {
PlatformInstance[i] =new Platform();
PlatformInstance[i].y= Math.random()*900;
PlatformInstance[i].x= Math.random() *1500;
stage.addChild(PlatformInstance[i]);
}
the code for my collisions and the scrolling is shown below:
for (i=0; i<8; i++) {
if (PlatformInstance[i].hitTestPoint (Smallclock_hero.x,Smallclock_hero.y+130,true)) {
yescollision = true;
if (keyboard_input.is_up() && yescollision == true)
{
trace ("boop")
Smallclock.y_speed = -40
yescollision = false;
}
else {
Smallclock.y_speed *= 0;
}
}
if (Scrolling == true) {
PlatformInstance[i].y += 1; // this moves the platforms down.
}
}
is there a simple and easy way to remove the PlatformInstance when it reaches a point say (1000) and then add the instance again, with the same randomization code?
thanks in advance.
Adding all of my class files for clarities sake, not sure if you will need them
Start.as
package com {
import flash.display.MovieClip;
import flash.events.Event;
public class Start extends MovieClip {
public var keyboard_input:Keys;
public var Smallclock_hero = new Smallclock;
public var BasePlatformInstance:BasePlatform = new BasePlatform;
public var BackgroundInstance:Background = new Background();
public var PlatformInstance:Platform = new Platform();
public var keyboard_sprite = new MovieClip();
public static var yescollision:Boolean = false
var yScrollSpeed:int = 1;
var Scrolling:Boolean = false;
var i:int =0;
public var Running:Boolean = true;
public function Start () {
trace("Hello")
addChild (BackgroundInstance);
addChild (Smallclock_hero);
addChild (BasePlatformInstance);
BasePlatformInstance.x = 0;
BasePlatformInstance.y = 980;
BackgroundInstance.height = stage.stageHeight +50 ;
BackgroundInstance.width = stage.stageWidth +50 ;
Smallclock_hero.init();
var keyboard_sprite = new MovieClip();
addChild (keyboard_sprite);
keyboard_input = new Keys (keyboard_sprite);
stage.addEventListener(Event.ENTER_FRAME,on_enter);
addEventListener (Event.ENTER_FRAME, collisions);
//addEventListener (Event.ENTER_FRAME,refreshPlatform)
for(i=0;i<8;i++) {
PlatformInstance[i] =new Platform();
PlatformInstance[i].y= Math.random()*900;
PlatformInstance[i].x= Math.random() *1500;
stage.addChild(PlatformInstance[i]);
}
}
public function on_enter(event:Event) {
if (keyboard_input.is_left()){
Smallclock_hero.apply_force(-1,0);
Smallclock_hero.scaleX = -1
}
if (keyboard_input.is_right()) {
Smallclock_hero.apply_force(1,0);
Smallclock_hero.scaleX = 1
}
}
public function collisions (e:Event) {
if (BasePlatformInstance.hitTestPoint (Smallclock_hero.x,Smallclock_hero.y+130, true)) {
//trace ("touching!")
yescollision = true;
if (keyboard_input.is_up())
{
Smallclock.y_speed = -40
Start.yescollision = false;
}
if (Smallclock.y_speed ==-40) {
Scrolling = true;
removeChild(BasePlatformInstance);
}
else {
Smallclock.y_speed *= 0;
}
}
for (i=0; i<8; i++) {
if (PlatformInstance[i].hitTestPoint (Smallclock_hero.x,Smallclock_hero.y+130, true)) {
yescollision = true;
if (keyboard_input.is_up() && yescollision == true)
{
trace ("boop")
Smallclock.y_speed = -40
yescollision = false;
}
else {
Smallclock.y_speed *= 0;
}
}
if (Scrolling == true) {
PlatformInstance[i].y += 1;
}
}
Smallclock.as
package com {
import flash.display.Sprite;
import flash.events.Event;
public class Smallclock extends Sprite {
private var x_speed:Number;
public static var y_speed:Number;
private var power:Number;
public var friction:Number;
public static var gravity:Number;
public static var jumping:Boolean = false;
public static var jumppwr:Number;
public static var jumpSpeedLimit:int = 15;
public function Smallclock() {
addEventListener (Event.ENTER_FRAME, move);
}
private function move (e:Event) {
x+=x_speed;
y+=y_speed;
y_speed += gravity
x_speed *= friction ;
y_speed *= friction ;
if (x < -25) {
x = 1650
}
if (x > 1650) {
x = -25
}
}
public function apply_force (x_force,y_force){
x_speed += (x_force*power);
y_speed += (y_force*power);
}
public function init() {
jumppwr = 2;
gravity = 1.0;
power = 0.8;
friction = 0.9;
x_speed = 0;
y_speed = 0;
x= stage.stageWidth/2;
y = 850;
}
}
}
Keys.as
package com {
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Keys {
private var press_left = false;
private var press_right = false;
private var press_up = false;
private var press_down = false;
private var press_space = false;
public function Keys(movieclip) {
movieclip.stage.addEventListener(KeyboardEvent.KEY_DOWN, key_down);
movieclip.stage.addEventListener(KeyboardEvent.KEY_UP, key_up);/**/
}
public function is_left() {
return press_left;
}
public function is_right() {
return press_right;
}
public function is_up() {
return press_up;
}
public function is_down() {
return press_down;
}
public function is_space() {
return press_space;
}
public function key_down(event:KeyboardEvent) {
if (event.keyCode == 32) {
press_space = true;
}
if (event.keyCode == 37) {
press_left = true;
}
if (event.keyCode == 38) {
press_up = true;
}
if (event.keyCode == 39) {
press_right = true;
}
if (event.keyCode == 40) {
press_down = true;
}
}
public function key_up(event:KeyboardEvent) {
if (event.keyCode == 32) {
press_space = false;
}
if (event.keyCode == 37) {
press_left = false;
}
if (event.keyCode == 38) {
press_up = false;
}
if (event.keyCode == 39) {
press_right = false;
}
if (event.keyCode == 40) {
press_down = false;
}
}
}
}
I am not going to read thru all your code, sorry.
Of course there is. In the interval/event handler where you are updating your positions, you have to loop through all your platforms and check whether their position is >= 1000. If it is, you don't need to remove it, just randomize it and set its position again with the code you already have:
for(i=0;i<8;i++) {
if(PlatformInstance[i].x >= 1000) {
var inst:Platform = PlatformInstance[i];
inst.y= Math.random() * 900;
inst.x= Math.random() * 1500;
}
That should work just fine. If you really need to remove it (??), you can do so with stage.removeChild(inst) and then stage.addChild(inst) again.
A few tips from that few code I read in your question: do not give instance/variable names with capitalized first letter. That should be a class name (PlatformInstance is obviously an instance of Array or Vector, use platformInstance). Do not add object directly to stage. If possible, add them to your stage owner (which is your document class if you write your code in classes).

ADDED_TO_STAGE Event doesn't work in certain frame?

This is Heli's Class and it'll called in main class ,the target of main class in frame 2 .
The frame 1 contain button that can make me go to frame 2 .but this movie clip of Heli doesn't added to the stage . but it'll work if i targeting main class in frame 1 . so can anyone tell me how to use added_to_stage event in specified frame ??? (sorry about my english)
package com.ply
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
public class Heli extends MovieClip
{
//Settings
public var xAcceleration:Number = 0;
public var yAcceleration:Number = 0;
private var xSpeed:Number = 0;
private var ySpeed:Number = 0;
private var up:Boolean = false;
private var down:Boolean = false;
private var left:Boolean = false;
private var right:Boolean = false;
private var bullets:Array;
private var missiles:Array;
public function Heli()
{
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function onAddedToStage(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
init();
}
private function init():void
{
stage.addEventListener(Event.ENTER_FRAME, runGame);
}
private function runGame(event:Event):void
{
xSpeed += xAcceleration ; //increase the speed by the acceleration
ySpeed += yAcceleration ; //increase the speed by the acceleration
xSpeed *= 0.95; //apply friction
ySpeed *= 0.95; //so the speed lowers after time
if(Math.abs(xSpeed) < 0.02) //if the speed is really low
{
xSpeed = 0; //set it to 0
//Otherwise I'd go very small but never really 0
}
if(Math.abs(ySpeed) < 0.02) //same for the y speed
{
ySpeed = 0;
}
xSpeed = Math.max(Math.min(xSpeed, 10), -10); //dont let the speed get bigger as 10
ySpeed = Math.max(Math.min(ySpeed, 10), -10); //and dont let it get lower than -10
this.x += xSpeed; //increase the position by the speed
this.y += ySpeed; //idem
}
}
}
public function Heli()
{
if (stage) init();
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
here it is the main class
package
{
import com.ply.Heli;
import com.peluru.Bullet;
import com.musuh.Airplane2;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.*;
import flash.utils.*;
public class Main extends MovieClip
{
public static const STATE_INIT:int = 10;
public static const STATE_START_PLAYER:int = 20;
public static const STATE_PLAY_GAME:int = 30;
public static const STATE_REMOVE_PLAYER:int = 40;
public static const STATE_END_GAME:int = 50;
public var gameState:int = 0;
public var player:Heli;
public var enemy:Airplane2;
//public var bulletholder:MovieClip = new MovieClip();
//================================================
public var cTime:int = 1;
//the time it has to reach in order to be allowed to shoot (in frames)
public var cLimit:int = 10;
//whether or not the user is allowed to shoot
public var shootAllow:Boolean = true;
//how much time before another enemy is made
public var enemyTime:int = 0;
//how much time needed to make an enemy
//it should be more than the shooting rate
//or else killing all of the enemies would
//be impossible :O
public var enemyLimit:int = 64;
//the player's score
public var score:int = 0;
public var gameOver:Boolean = false;
public var bulletContainer:MovieClip = new MovieClip();
//================================================
public function Main()
{
//stage.addEventListener(Event.ENTER_FRAME, gameLoop);
// instantiate car class
gameState = STATE_INIT;
gameLoop();
}
public function gameLoop(): void {
switch(gameState) {
case STATE_INIT :
initGame();
break
case STATE_START_PLAYER:
startPlayer();
break;
case STATE_PLAY_GAME:
playGame();
break;
case STATE_REMOVE_PLAYER:
//removePlayer();
break;
case STATE_END_GAME:
break;
}
}
public function initGame() :void {
//addChild(bulletholder);
addChild(bulletContainer);
gameState = STATE_START_PLAYER;
gameLoop();
stage.addEventListener(KeyboardEvent.KEY_DOWN, myOnPress);
stage.addEventListener(KeyboardEvent.KEY_UP, myOnRelease);
stage.addEventListener(Event.ENTER_FRAME, AddEnemy);
}
public function startPlayer() : void {
player=new Heli();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
// add car to display list
stage.addChild(player);
gameState = STATE_PLAY_GAME;
}
public function playGame():void {
//CheckTime();
gameLoop();
//txtScore.text = 'Score: '+score;
}
public function myOnPress(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
player.xAcceleration = -1;
}
else if(event.keyCode == Keyboard.RIGHT)
{
player.xAcceleration = 1;
}
else if(event.keyCode == Keyboard.UP)
{
player.yAcceleration = -1;
}
else if(event.keyCode == Keyboard.DOWN)
{
player.yAcceleration = 1;
}
else if (event.keyCode == 32 && shootAllow)
{
fireBullet();
}
}
public function fireBullet() {
//making it so the user can't shoot for a bit
shootAllow = false;
//declaring a variable to be a new Bullet
var newBullet:Bullet = new Bullet();
var newBullet2:Bullet = new Bullet();
//changing the bullet's coordinates
newBullet.x = player.x+20; //+ player.width/2 - player.width/2;
newBullet.y = player.y;
newBullet2.x = player.x-20;
newBullet2.y = player.y;
//then we add the bullet to stage
bulletContainer.addChild(newBullet);
bulletContainer.addChild(newBullet2);
}
function AddEnemy(event:Event){
if(enemyTime < enemyLimit){
//if time hasn't reached the limit, then just increment
enemyTime ++;
} else {
//defining a variable which will hold the new enemy
enemy =new Airplane2();
//making the enemy offstage when it is created
enemy.y = -1 * enemy.height;
//making the enemy's x coordinates random
//the "int" function will act the same as Math.floor but a bit faster
enemy.x = Math.floor(Math.random()*(stage.stageWidth - enemy.width));
//then add the enemy to stage
addChild(enemy);
//and reset the enemyTime
enemyTime = 0;
}
if(cTime <= cLimit){
cTime ++;
} else {
//if it has, then allow the user to shoot
shootAllow = true;
//and reset cTime
cTime = 1;
}
}
public function myOnRelease(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.RIGHT)
{
player.xAcceleration = 0;
}
else if(event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN)
{
player.yAcceleration = 0;
}
}
}
}

Stopping a function to run more than once in a period of time

I have this MouseEvent function that I have totally no idea why it fired twice. Is there a way I can disable the function in a period of time? I tried disabling the button, but seems like it directly called the function and does not trigger from the button.
Addition info:When I add in more object to the array, the function fired more time
The Class the handles the button
package classes
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import classes.playVideo;
import classes.playList;
import classes.viewType;
public class controlMenu extends MovieClip
{
private var playV:playVideo=new playVideo();
private var list:playList=new playList();
private var viewT:viewType = new viewType();
private static var con:controls = new controls();
private static var _buttonStatus:Boolean;
public function controlMenu()
{
}
//-------------------------------------------------------------
public function loadControlMenu():void
{
this.addEventListener(Event.ADDED_TO_STAGE,add2Stage);
}
private function add2Stage(e:Event):void
{
if (stage.numChildren == 1)
{
con.x=(stage.stageWidth-230)/2;
con.y=stage.stageHeight-(con.height+9);
addChild(con);
playButtonStatus();
con.soundBtn.addEventListener(MouseEvent.MOUSE_OVER, soundOver);
con.soundBtn.addEventListener(MouseEvent.MOUSE_OUT, soundOut);
con.soundBtn.addEventListener(MouseEvent.MOUSE_DOWN, soundDown);
stage.addEventListener(MouseEvent.MOUSE_UP, soundUp);
con.prev.addEventListener(MouseEvent.CLICK,prevClick);
con.next.addEventListener(MouseEvent.CLICK,nextClick);
}
}
private function playClick(e:MouseEvent):void
{
if (e.currentTarget.currentFrameLabel == "play" && playV.currentVideoStatus == "play")
{
e.currentTarget.gotoAndStop("pause");
playV.pauseStatus();
}
else if (e.currentTarget.currentFrameLabel=="pause" && playV.currentVideoStatus == "pause")
{
e.currentTarget.gotoAndStop("play");
playV.playStatus();
}
else if (e.currentTarget.currentFrameLabel == "play"&& playV.currentVideoStatus == "end")
{
playV.newVideo = "video/video" + list.currentIndex + ".flv";
}
}
private function playOver(e:MouseEvent):void
{
e.currentTarget.btn.gotoAndStop("over");
}
private function playOut(e:MouseEvent):void
{
e.currentTarget.btn.gotoAndStop("out");
}
//-------------------------------------------------------------
private function soundOver(e:MouseEvent):void
{
e.currentTarget.gotoAndStop("over");
}
private function soundOut(e:MouseEvent):void
{
if (e.buttonDown == false)
{
e.currentTarget.gotoAndStop("out");
}
}
private function soundDown(e:MouseEvent):void
{
var volumeBound:Rectangle = new Rectangle(-93,35,80,0);
e.currentTarget.startDrag(false, volumeBound);
stage.addEventListener(MouseEvent.MOUSE_MOVE,soundAdjust);
}
private function soundUp(e:MouseEvent):void
{
con.soundBtn.stopDrag();
con.soundBtn.gotoAndStop("out");
stage.removeEventListener(MouseEvent.MOUSE_MOVE,soundAdjust);
}
private function soundAdjust(e:MouseEvent):void
{
playV.adjustSound = ((con.soundBtn.x+93)*100)/80;
}
public function set adjustSoundBtnPos(a:Number):void
{
var newPos:Number = ((80*a)/100);
con.soundBtn.x = newPos - 93;
}
private function prevClick(e:MouseEvent):void
{
if (viewT.viewIn == "stream" && list.currentIndex > 1)
{
var goBack = list.currentIndex - 1;
list.currentIndex = goBack;
playV.newVideo = "video/video" + goBack + ".flv";
list.currentVideoLink = goBack;
}
}
private function nextClick(e:MouseEvent):void
{
if (viewT.viewIn == "stream" && list.currentIndex < list.vDataLength)
{
var goNext = list.currentIndex + 1;
list.currentIndex = goNext;
playV.newVideo = "video/video" + goNext + ".flv";
list.currentVideoLink = goNext;
}
}
//-------------------------------------------------------------
public function get currentStatus():String
{
return con.playBtn.currentFrameLabel;
}
public function resetPlayStatus():void
{
con.playBtn.gotoAndStop("play");
}
//-------------------------------------------------------------
public function set buttonStatus(s:Boolean):void
{
_buttonStatus = s;
playButtonStatus();
}
public function playButtonStatus():void
{
if (_buttonStatus == true)
{
con.playBtn.buttonMode = true;
con.playBtn.addEventListener(MouseEvent.CLICK, playClick);
con.playBtn.addEventListener(MouseEvent.MOUSE_OVER, playOver);
con.playBtn.addEventListener(MouseEvent.MOUSE_OUT, playOut);
con.soundBtn.buttonMode = true;
con.soundBtn.mouseEnabled = true;
}
else
{
con.playBtn.buttonMode = false;
con.playBtn.removeEventListener(MouseEvent.CLICK, playClick);
con.playBtn.removeEventListener(MouseEvent.MOUSE_OVER, playOver);
con.playBtn.removeEventListener(MouseEvent.MOUSE_OUT, playOut);
con.soundBtn.buttonMode = false;
con.soundBtn.mouseEnabled = false;
}
}
}
}
The Class that cause the extra loop on mouseevent function
package classes
{
import flash.media.Video;
import flash.display.MovieClip;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.events.AsyncErrorEvent;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.utils.Timer;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.media.SoundTransform;
import flash.media.SoundMixer;
import flash.net.URLLoader;
import flash.net.URLRequest;
import classes.Playing;
import classes.progressBar;
import classes.controlMenu;
import classes.viewType;
import classes.downloadVideo;
import classes.playList;
import classes.playVideo;
public class playVideo extends MovieClip
{
private var Play:Playing = new Playing();
private var progressB:progressBar = new progressBar();
private var conM:controlMenu;
private var viewT:viewType=new viewType();
private var downloadV:downloadVideo;
private var list:playList;
private var vBox:MovieClip = new MovieClip();
private var nc:NetConnection;
private static var ns:NetStream;
private const buffer:Number = 2;
private static var videoURL:String;
private static var vid:Video = new Video();
private static var meta:Object = new Object();
private var durationSecs:Number;
private var durationMins:Number;
private var durSecsDisplay:String;
private var durMinsDisplay:String;
private static var videoDuration:String;
private static var t:Timer = new Timer(100);
private static var videoSound:SoundTransform = new SoundTransform();
private var arial:Arial = new Arial();
private static var durationTxt:TextField=new TextField();
private var durationTxtF:TextFormat=new TextFormat();
private var scrubForward:Boolean;
private static var currentStatus;
private static var nsArray:Array= new Array();
private var dummyArray:Array = new Array();
//--------------------------------------------------------------------------
private var videoLoader:URLLoader;
public function playVideo()
{
}
public function set newVideo(v:String):void
{
currentStatus = "play";
videoURL = v;
if (viewT.viewIn == "stream")
{
addVideo();
}
else if (viewT.viewIn=="download")
{
for (var i:uint=0; i<nsArray.length; i++)
{
if (nsArray[i] != null)
{
nsArray[i].close();
}
}
videoProperties();
soundF();
}
conM.resetPlayStatus();
}
public function videoFunction():void
{
vBox.graphics.beginFill(0x000000);
vBox.graphics.drawRect(0,36,668,410);
vBox.graphics.endFill();
addChild(vBox);
// Add the instance of vid to the stage
vid.width = vid.width * 2;
vid.height = vid.height * 1.5;
vid.x = vBox.width / 2 - vid.width / 2;
vid.y = vBox.height / 2 - vid.height / 2 + 36;
vBox.addChild(vid);
if (viewT.viewIn == "stream")
{
videoProperties();
}
soundF();
durationText();
}
public function videoProperties():void
{
nc=new NetConnection();
// Assign variable name for Net Connection
nc.connect(null);
// Assign Var for the NetStream Object using NetConnection
ns = new NetStream(nc);
// Add the buffer time to the video Net Stream
ns.bufferTime = buffer;
// Set client for Meta Data Function
ns.client = {};
ns.client.onMetaData = onMetaData;
// Attach netStream to our new Video Object
if (viewT.viewIn == "stream")
{
vid.attachNetStream(ns);
}
else if (viewT.viewIn == "download")
{
nsArray[list.currentIndex - 1] = ns;
dummyArray.push(ns);
vid.attachNetStream(ns);
}
addVideo();
}
private function addVideo():void
{
// Assign NetStream to start play automatically by default
if (viewT.viewIn == "stream" && videoURL == null)
{
videoURL = "video/video1.flv";
}
ns.play(videoURL);
conM= new controlMenu();
conM.buttonStatus = true;
progressB.progressBarStatus();
// Add Error listener and listeners for all of our buttons
ns.addEventListener(AsyncErrorEvent.ASYNC_ERROR,asyncErrorHandler);
currentStatus = "play";
t.addEventListener(TimerEvent.TIMER,onTick);
t.start();
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
// Do whatever you want if an error arises
}
private function onMetaData(info:Object):void
{
meta = info;
/*for (meta in info)
{
trace(meta + ":" + info[meta]);
}*/
durationSecs = Math.floor(meta.duration);
durationMins = Math.floor(durationSecs / 60);
durationMins %= 60;
durationSecs %= 60;
if (durationMins < 10)
{
durMinsDisplay = "0" + durationMins;
}
else
{
durMinsDisplay = "" + durationMins;
}
if (durationSecs < 10)
{
durSecsDisplay = "0" + durationSecs;
}
else
{
durSecsDisplay = "" + durationSecs;
}
videoDuration = durMinsDisplay + ":" + durSecsDisplay;
Play.vDuration = videoDuration;
}
//--------------------------------------------------------------------------
public function prepareArray():void
{
list = new playList();
for (var i:uint=0; i<list.vDataLength; i++)
{
nsArray.push(null);
}
}
//--------------------------------------------------------------------------
private function onTick(event:TimerEvent):void
{
if (viewT.viewIn == "stream" || ns.bytesLoaded == ns.bytesTotal)
{
var nsSecs:Number = Math.floor(ns.time);
var nsMins:Number = Math.floor(nsSecs / 60);
nsMins %= 60;
nsSecs %= 60;
var nsSecsDisplay:String = "";
var nsMinsDisplay:String = "";
if (nsMins < 10)
{
nsMinsDisplay = "0" + nsMins;
}
else
{
nsMinsDisplay = "" + nsMins;
}
if (nsSecs < 10)
{
nsSecsDisplay = "0" + nsSecs;
}
else
{
nsSecsDisplay = "" + nsSecs;
}
durationTxt.text = nsMinsDisplay + ":" + nsSecsDisplay;
progressB.progressing = ns.time / meta.duration * 668;
}
else if (viewT.viewIn=="download" && ns.bytesLoaded!=ns.bytesTotal)
{
list.preloadFlv();
}
if (durationTxt.text == videoDuration)
{
currentStatus = "end";
t.stop();
t.removeEventListener(TimerEvent.TIMER,onTick);
ns.pause();
ns.seek(0);
}
}
//--------------------------------------------------------------------------
private function soundF():void
{
var soundAmount:Number = 7;
if (viewT.viewIn == "stream")
{
ns.soundTransform = videoSound;
videoSound.volume = soundAmount / 10;
conM.adjustSoundBtnPos = soundAmount * 10;
}
else if (viewT.viewIn=="download")
{
if (dummyArray.length == 1 && ns != null)
{
ns.soundTransform = videoSound;
videoSound.volume = soundAmount / 10;
conM.adjustSoundBtnPos = soundAmount * 10;
}
else if (dummyArray.length> 1 && ns!=null)
{
ns.soundTransform = videoSound;
}
}
}
public function set adjustSound(s:Number):void
{
videoSound.volume = s / 100;
ns.soundTransform = videoSound;
}
//--------------------------------------------------------------------------
private function durationText():void
{
durationTxtF = new TextFormat();
durationTxtF.size = 12;
durationTxtF.leftMargin = 5;
durationTxtF.font = arial.fontName;
durationTxt.defaultTextFormat = durationTxtF;
durationTxt.selectable = false;
durationTxt.textColor = 0x999999;
durationTxt.width = 50;
durationTxt.height = 22;
durationTxt.x = 476;
durationTxt.y = 477;
durationTxt.text = "00:00";
addChild(durationTxt);
}
//--------------------------------------------------------------------------
public function get Duration():String
{
return videoDuration;
}
public function playStatus():void
{
conM=new controlMenu();
if (conM.currentStatus == "play")
{
ns.resume();
updateProgress();
}
if (currentStatus == "pause")
{
currentStatus = "play";
t.start();
}
}
public function pauseStatus():void
{
ns.pause();
t.stop();
trace("pause");
if (currentStatus == "play")
{
currentStatus = "pause";
}
}
public function get currentVideoStatus():String
{
return currentStatus;
}
public function restartVideo():void
{
ns.resume();
}
//--------------------------------------------------------------------------
public function updateProgress():void
{
ns.seek((progressB.currentProgress / 668) *meta.duration);
}
public function get nsBytesTotal():Number
{
return ns.bytesTotal;
}
public function get nsBytesLoaded():Number
{
return ns.bytesLoaded;
}
public function get getVideoURL():String
{
return videoURL;
}
}
}
I strongly, strongly recommend against doing some sort of flag or timer hack to get around an unexplained behavior - that leads to code bloat and down the line it'll cause you more problems in the long run.
It's much, much, much better to understand why it's calling your function twice. Invest the time in figuring that out (do you have listeners set on multiple display objects? Is this some sort of bubbling issue? Could it be your mouse? Try a clean flash project with just a handler and see if that calls twice, etc), and not only will your code be better and faster but you'll also learn a lot in the process.
You could make a variable so it only runs once. Something like...
var runOnce:Boolean = false;
button.addEventListener(MouseEvent.CLICK, testEvent);
function testEvent(e:Event):void{
if(runOnce == false){
//do stuff here
runOnce = true;
}
It's a bit lazy, but you get the idea.