Initialize the code (in a actionscript file) in a different frame - actionscript-3

How can I initialize this game in a differente frame with the function init? I'm working in Actionscript 3.0.
Hope you can help me.
Heres the code (the code is in a actionscript file) :
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; //used for ENTER_FRAME event
public class Main extends MovieClip{
//constants
const gravity:Number = 1.5; //gravity of the game
const dist_btw_obstacles:Number = 300; //distance between two obstacles
const ob_speed:Number = 8; //speed of the obstacle
const jump_force:Number = 15; //force with which it jumps
//variables
var player:Player = new Player();
var lastob:Obstacle = new Obstacle(); //varible to store the last obstacle in the obstacle array
var obstacles:Array = new Array(); //an array to store all the obstacles
var yspeed:Number = 0; //A variable representing the vertical speed of the bird
var score:Number = 0; //A variable representing the score
public function Main(){
init();
}
function init():void {
//initialize all the variables
player = new Player();
lastob = new Obstacle();
obstacles = new Array();
yspeed = 0;
score = 0;
//add player to center of the stage the stage
player.x = stage.stageWidth/2;
player.y = stage.stageHeight/2;
addChild(player);

If there are frame (for Adobe Animate projects), use addFrameScript:
someMC.addFrameScript(2, myFunction);
private function myFunction():void{
this.stop();
}
myFunction work if frame 2 would have existed.
If not, you can use Tween frameworks like TweenLite or TweenMax (Recommended):
TweenLite.to(mc, 1.5, {onComplete:myFunction});
function myFunction():void {
trace("tween finished");
}
myFunction is run after 1.5 sec

Related

Updating and displaying a variable in AS3

I have been following an AS3 tutorial for an avoider game, the trouble is the tutorial is for CS5 and I am using Flash Develop. I am completely stuck trying to update and display the score. I have read through several posts on SO and elsewhere and still can't seem to fix it.
Here is the Score class that I call to display the score and it contains the function that updates the "score" value.
package
{
import flash.display.Sprite;
import flash.events.TextEvent;
import flash.text.TextField
import flash.text.TextFormat
public class Score extends Sprite
{
public var scoreDisplay:String;
public var currentValue:int;
public function Score()
{
updateDisplay()
}
public function updateDisplay():void
{
scoreDisplay = currentValue.toString();
var format:TextFormat = new TextFormat();
format.size = 25;
format.font = "Verdana"
var myText:TextField = new TextField();
myText.defaultTextFormat = format;
myText.text = scoreDisplay;
myText.background = true;
myText.autoSize
myText.width = 50;
myText.height = 35;
addChild(myText)
myText.x = 340
myText.y = 10
myText.mouseEnabled = false
}
public function addToValue( amountToAdd:Number ):void
{
trace("addToValue")
trace(currentValue)
currentValue = currentValue + amountToAdd;
trace(currentValue + " 1")
}
}
}
and here is the Game class I am running to increase the "score" per tick.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.Timer;
import Score;
public class Game extends Sprite
{
public var army:Array;
public var gameTimer:Timer;
public var player:Player;
public var background:Sprite;
public function Game()
{
army = new Array();
var newenemy:Enemy = new Enemy(100, -15);
army.push(newenemy);
addChild(newenemy);
player = new Player();
addChild(player);
player.x = mouseX;
player.y = mouseY;
gameTimer = new Timer(20);
gameTimer.addEventListener(TimerEvent.TIMER, move);
gameTimer.addEventListener(TimerEvent.TIMER, onTick);
gameTimer.start();
}
private function move(timerEvent:TimerEvent):void
{
player.x = mouseX;
player.y = mouseY;
for each (var enemy:Enemy in army)
{
enemy.moveDownABit();
if (player.hitTestObject(enemy))
{
gameTimer.stop();
dispatchEvent( new AvatarEvent( AvatarEvent.DEAD));
}
}
}
public function onTick(e:Event):void
{
if (Math.random() < .1)
{
var randomX:Number = Math.random() * 400;
var newEnemy:Enemy = new Enemy(randomX, -15);
army.push(newEnemy);
addChild(newEnemy);
var instanceScore:Score = new Score();
instanceScore.addToValue(10)
}
}
}
}
My trace function outputs "addToValue, 0, 10 1" and repeats that, never changing the 'curentValue' variable past 0. I can tell that the 'amountToAdd' is functioning properly but have no idea why 'currentValue' is always reset to 0.
questions on SO that I viewed;
Display dynamic variable on next key frame AS3
Avoider Game Tutorial: Score not working
The problem is this:
var instanceScore:Score = new Score();
This means that every time there is a tick, you create new score. When you create new score, it starts from 0. You update it to 10, and on the next tick, you ignore the old value of 10 by creating a whole new class. The new class has a value of 0, as it never has it's value increased before. Then you increase it again.. and a new tick starts (looping)
What you need to do is to instantiate score instance ONLY ONCE and save it as a class member variable. Then you can call increase to it.

AS3 Turret and bullet error

I have been struggling with a as3 and flash game that i am trying to make. Everything looks fine, but still the bullet are stuck inside the cannon. When i use my mouse to shoot, instead of going out to a location, it just get stuck inside the cannon:
Got 3 as3 documents, and one flash document:
Ships.as
package{
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Point;
public class Ship extends Sprite{
private var speed:int;
private var target:Point;
function Ship(){
speed=2+Math.random()*5;
//trace("Made a Ship!");
//set the target for the ships
target = new Point(Math.random()*500, Math.random()*500);
//target.x = Math.random()*500;
//target.y = Math.random()*500;
//addEventListener(Event.ENTER_FRAME, update);
}
function update(){
//Set the ships to point the target
var dx = target.x - x;
var dy = target.y - y;
var angle = Math.atan2(dy, dx)/Math.PI*180;
rotation = angle;
x=x+Math.cos(rotation/180*Math.PI)*speed;
y=y+Math.sin(rotation/180*Math.PI)*speed;
//New target
var hyp = Math.sqrt((dx*dx)+(dy*dy));
if(hyp < 5){
target.x = Math.random()*500;
target.y = Math.random()*500;
}
}
}
}
Game.as
package{
import flash.display.MovieClip;
import flash.events.Event;
public class Game extends MovieClip{
var ships:Array;
public function Game(){
trace("Made that game!");
addEventListener(Event.ENTER_FRAME, loop);
//set up the ship array
ships = new Array();
}
function loop(e:Event){
if(numChildren<10){
var s = new Ship();
addChild(s);
s.x = Math.random()*stage.stageWidth;
s.y = Math.random()*stage.stageHeight;
s.rotation = Math.random()*360;
//Add the ship to the list of ships
ships.push(s);
}
//Make a for loop to iterate through all the ship
for(var count=0; count<ships.length; count++){
ships[count].update();
//Add a new for loop to go through all the bullets
}
}
}
}
}
}
Turret.as
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Turret extends MovieClip{
//Properties goes here
var shotCooldown:int;
var bullets:Array;
const MAX_COOLDOWN = 10;
public function Turret(){
//Set the Shot Cooldown
shotCooldown = MAX_COOLDOWN;
bullets = new Array();
addEventListener(Event.ENTER_FRAME, update);
addEventListener(Event.ADDED_TO_STAGE, initialise);
}
function initialise(e:Event)
{
stage.addEventListener(MouseEvent.CLICK, fire);
}
function fire(m:MouseEvent)
{
//If we are allowed to shoot
if(shotCooldown<=0)
{
//Reset the Shot Cooldown
shotCooldown=MAX_COOLDOWN;
//Spawn a Bullet
var b = new Bullet();
b.rotation = rotation;
b.x = x;
b.y = y;
//Add the bullet to the list of bullets
bullets.push(b);
parent.addChild(b);
play();
}
}
function update(e:Event)
{
//Reduce the Shot Cooldown by 1
//shotCooldown=shotCooldown-1;
//shotCooldown-=1;
shotCooldown--;
if(parent != null)
{
var dx = parent.mouseX - x;
var dy = parent.mouseY - y;
var angle = Math.atan2(dy, dx) / Math.PI * 180;
rotation = angle;
}
}
}
}
They are stuck in place maybe because you are not moving them at all? If you are then please show me where. Try adding to the turret's enter frame event the following code:
for (var a:int = 0; bullets.length > a ; a++)
{
var temp:MovieClip;
temp = bullets[a] as Bullet;
var vel:Point = new Point();
vel.x = temp.target.x-temp.x;
vel.y = temp.target.y-temp.y;
vel.normalize(4);
temp.x += vel.x;
temp.y += vel.y;
}
And make an as file for the Bullet Class and add this:
package
{
import flash.geom.Point;
public class Bullet extends MovieClip
{
public var target:Point = new Point();
public function Bullet()
{
target.x = stage.mouseX;
target.y = stage.mouseY;
}
}
}
In Turret class bullets are added to the stage and array but doesn't have updated every frame like ships. See your own comment about updating bullets!

How can i create movieclip from png what is imported to a array?

i would import jpg files from the library and put them into an array. after this i would place them on the stage and apply event listener on them.
or how can i add event listener to the array?
sry for my english. thank u for help
import flash.utils.getDefinitionByName;
import flash.display.Bitmap;
import flash.display.MovieClip;
import flash.display.BitmapData;
import com.bitmap.InteractivePNG;
import flash.display.Sprite;
var polc1Ar:Array = new Array();
inditasFu();
function inditasFu(){
behivas();
rakdkiFu();
}
function behivas(){
for (var i=1; i!=3; i++) {
var ClassRef:Class = getDefinitionByName("elsok" + i.toString()) as Class;
var classRef = new ClassRef();
classref.alphaTolerance = 255;
classref.smoothing = true;
classref.pixelSnapping = "never";
polc1Ar.push(classRef)
}
}
function rakdkiFu (){
for (var i=0; i!=polc1Ar.length; i++){
var monci:Sprite= new Sprite;
monci=polc1Ar[i];
monci.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownFu);
monci.addEventListener(MouseEvent.MOUSE_UP, mouseUpFu);
}
}
function mouseDownFu(e:MouseEvent):void{
var mc:MovieClip = MovieClip(e.target);
mc.startDrag(false);
mc.alpha = .55;
this.addChild(mc);
}
function mouseUpFu(e:MouseEvent):void{
var mc:MovieClip = MovieClip(e.target);
mc.stopDrag();
mc.alpha = 1;
}
monci=polc1Ar[i]; You are assigning a bitmap there to a Sprite. Instead, create a new Sprite, add the bitmap to it with addChild and manipulate the sprite instances instead of the bitmaps. Anyway you will need an InteractiveObject instance for the mouse events and Bitmap is not one.

Correct usage of addtoStage when loading external swf

I am loading an external swf file into a parent swf file.
Previously, I was getting error 1009 and fixed that by using a listener event to add the swf to the stage before running any scripts.
The swf however fails to load completely when embedded into a parent swf as seen in this URL
http://viewer.zmags.com/publication/06b68a69?viewType=pubPreview#/06b68a69/1
Here is the code I am using.
Thank you for any input.
package
{
import com.greensock.TweenLite;
import flash.display.DisplayObject;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.SpreadMethod;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
public class slider5 extends Sprite
{
public var thumbPath:String = "Trailchair_thumb";
public var featPath:String = "Trailchair";
public var sliderIndex:Number = 1;
public var currBg:Bitmap = new Bitmap();
public var thumbCount:Number = 8;
public var thumbHolder:Sprite = new Sprite();
public var thumbMask:Sprite = new Sprite();
public var thumbX:Number = 0;
public var thmPadding:Number = 10;
public var thmWidth:Number;
public var navLeft:Sprite = new Sprite();
public var navRight:Sprite = new Sprite();
public var timer:Timer = new Timer(5000,0);
public var sliderDir:String = "fwd";
public function slider5()
{
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function onAddedToStage(e:Event):void{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
//THE BACKGROUND IMAGE
currBg.alpha = 1;
stage.addChildAt(currBg, 0);
changeBg(sliderIndex);
//The thumbMask a sprite with graphic rectangle
thumbMask.x = 87;
thumbMask.y = 572;
thumbMask.graphics.beginFill(0xFFFFFF);
thumbMask.graphics.drawRect(0,0, 406, 181);
stage.addChildAt(thumbMask, 2);
//The thumbSlider
thumbHolder.x = 228;
thumbHolder.y = 573;
stage.addChildAt(thumbHolder, 1);
thumbHolder.mask = thumbMask;
buildThumbs();
//add the nav
navLeft.x = 100;
navLeft.y = 609;
navRight.x = 496;
navRight.y = 609;
stage.addChildAt(navLeft, 4);
stage.addChildAt(navRight, 4);
var navBmp:Bitmap = new Bitmap();
navBmp.bitmapData = new navarrow(109,109);
var navBmp_Rt:Bitmap = new Bitmap();
navBmp_Rt.bitmapData = new navarrow(109,109);
navLeft.addChild(navBmp);
navLeft.scaleX *= -1;
navRight.addChild(navBmp_Rt);
navLeft.useHandCursor = true;
navLeft.buttonMode = true;
navRight.useHandCursor = true;
navRight.buttonMode = true;
navLeft.name = "left";
navRight.name = "right";
navLeft.addEventListener(MouseEvent.CLICK, navClick);
navRight.addEventListener(MouseEvent.CLICK, navClick);
//add the active item frame
var frame:Sprite = new Sprite();
frame.x = 226;
frame.y = 570;
frame.graphics.lineStyle(10, 0x000000);
frame.graphics.drawRect(0,0,131, 181);
stage.addChildAt(frame, 6);
timer.addEventListener(TimerEvent.TIMER, timeEvt);
timer.start();
}
public function changeBg(index):void
{
//set the first slide from our library and add to the stage
var currBg_Class:Class = getDefinitionByName( featPath + index ) as Class;
currBg.bitmapData = new currBg_Class(597,842);
//fade it in
TweenLite.from(currBg, 0.5, {alpha:0});
}
public function buildThumbs():void
{
var currThm:Class;
for (var i:uint = 1; i<=thumbCount; i++)
{
currThm = getDefinitionByName( thumbPath + i ) as Class;
var thmBmp:Bitmap = new Bitmap();
thmBmp.bitmapData = new currThm(126,176);
thmBmp.x = thumbX;
thumbHolder.addChild(thmBmp);
thumbX += thmBmp.width + thmPadding;
}
thmWidth = thmBmp.width + thmPadding;
}
public function navClick(e):void
{
timer.reset();
timer.start();
var dir:String = e.currentTarget.name;
if (dir=="left" && thumbHolder.x < 228 )
{
sliderIndex--;
TweenLite.to(thumbHolder, 0.5, {x:thumbHolder.x + thmWidth});
//thumbHolder.x = thumbHolder.x + thmWidth;
}
else if (dir=="right" && thumbHolder.x > - 724 )
{
sliderIndex++;
TweenLite.to(thumbHolder, 0.5, {x:thumbHolder.x - thmWidth});
//thumbHolder.x = thumbHolder.x - thmWidth;
}
if (sliderIndex == thumbCount)
{
sliderDir = "bk";
}
if (sliderIndex == 1)
{
sliderDir = "fwd";
}
changeBg(sliderIndex);
}
public function timeEvt(e):void
{
if (sliderDir == "fwd")
{
navRight.dispatchEvent(new Event(MouseEvent.CLICK));
}
else if (sliderDir == "bk")
{
navLeft.dispatchEvent(new Event(MouseEvent.CLICK));
}
}
}
}
If you still need it you can try these two suggestions. Note I didnt know about Zmags and initially assumed that it was your own domain name. That's why I suggested you use the Loader class. It worked for me when I did a test version of a parent.swf' that loaded a test 'child.swf' containing your code. It actually loaded the child swf without problems.
Change from extending Sprite to extending MovieClip
Avoid checking for added to stage in this project
Explanations:
Extending MovieClip instead of Sprite
I Long story short Flash wont like your swf extending Sprite then being opened by a parent loader that extends Movieclip. The ZMag player will be extending MovieClip. It's logical and the docs do confirm this in a way. Whether it fixes your issue or not just keep it MovieClip when using ZMags.
Avoiding Stage referencing in your code..
Looking at this Zmags Q&A documentaion:
http://community.zmags.com/articles/Knowledgebase/Common-questions-on-flash-integration
Looking at Question 4.. In their answer these two stand out.
Reference of the stage parameter in the uploaded SWF conflicting with the publication
Badly or locally referenced resources in the SWF you uploaded which cannot be found
Is it really necessary to have an added_to_stage check in this? If it wont hurt then I suggest dropping the stage_added checking from function slider5() and instead cut/paste in there the code you have from the function onAddedToStage(e:Event).
Hope it helps.

PaperVision3D and Flash CS4

I need to develop a cube that contain 10 little cubes and manipulate everyone like an object..Somebody have any idea or some tutorial for do this on PaperVision3d and Flash CS4..Thanks Folks!!
I think what you actually want is Papervision3d as I know of nothing called "PaperViewer". If that is the case, please update your question.
This should give you an idea of how to start. It creates 10 cubes and stores them in an array. You can access them using boxes[index] to alter their scale, postion and rotation.
package
{
import flash.display.Sprite;
import flash.events.Event;
import org.papervision3d.cameras.Camera3D;
import org.papervision3d.materials.ColorMaterial;
import org.papervision3d.materials.utils.MaterialsList;
import org.papervision3d.objects.primitives.Cube;
import org.papervision3d.view.BasicView;
public class Boxes3d extends Sprite
{
private static const NUM_BOXES:int = 10;
private var world:BasicView;
private var boxes:Array;
public function Boxes3d()
{
addEventListener(Event.ADDED_TO_STAGE, addedToStage);
}
private function addedToStage(event:Event):void
{
// create the world and add it to the stage
world = new BasicView();
addChild(world);
// create a set of boxes
boxes = [];
var box:Cube;
var materials:MaterialsList;
for(var boxIndex:int = 0; boxIndex < NUM_BOXES; boxIndex++)
{
// create a material to cover the cube
materials = new MaterialsList({
all: new ColorMaterial(Math.random()*0xFFFFFF) });
// make a cube
box = new Cube(materials, 100, 100, 100);
// spread it out in space
box.x = Math.random()*500 - 250;
box.y = Math.random()*500 - 250;
box.z = Math.random()*500 - 250;
// add it to the scene
world.scene.addChild(box);
}
// get the world to render each frame
world.startRendering();
addEventListener(Event.ENTER_FRAME, positionCamera);
}
private function positionCamera(event:Event):void
{
var camera:Camera3D = world.cameraAsCamera3D;
camera.x = -(stage.width/2 - mouseX) * 2;
camera.y = (stage.height/2 - mouseY) * 2;
}
}
}