AS3 creating new instances from blueprints - actionscript-3

I'm learning how classes work, it's pretty complicated. I need an example of a right object creation. Let's say I have a MovieClip blueprint in my library. It can be used as an example to create many instances with names that can further be used as objects in code to change their properties. So pretend I have a blueprint "AppleBP". I set it as Apple class (assume, it creates a file Apple.as?). I need a code that would create (by pushing a button, for example) an instance Apple01 that would appear at a random place on the screen (just to know it's different from others, I know how to randomize position). Then make Apple02, Apple03, Apple04 and Apple05. If it's hard to set name to "Apple" + N, it's ok to stick to an array with names or at least pick it like if(N = 1){//code for Apple01 creation} then N++ etc.
So for now I tried
var Apple01:Apple = new Apple();
Apple01.visible = true; //just in case I can't see it
Apple01.x = 100;
Apple01.y = 100;
TextField01.text = "blahblah"; //to see if code actually works
Apple doesn't appear, text does. So what am I missing if creating a new class that is a MovieClip blueprint isn't enough? And how would I pick new names for each new instance so that it had variable String instead of pure name? (so that I could change the name as text + number based on it's order)
Add:
package {
import flash.display.Scene;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.events.*;
import flash.display.*;
public class MyFirstClass extends MovieClip{
//var N:int;
var n:int;
var existingApples:int = 0;
var apples:Array = new Array();
public function MyFirstClass():void{
MakeNewApple();
MakeNewApple();
MakeNewApple();
MakeNewApple();
MakeNewApple();
//apple4.x = 5;
//apple4.y = 5;
var draggableApple:Apple = apples[0] ;
draggableApple.addEventListener(MouseEvent.MOUSE_DOWN, draggableApple.onMouseDown) ;
draggableApple.addEventListener(MouseEvent.MOUSE_UP, draggableApple.onMouseUp) ;
info01.text = "Did it";
}
public function MakeNewApple():void{
if(existingApples < 5){
n = existingApples;
var apple:Apple = new Apple();
stage.addChild(apple);
apple.x = (Math.random()*600+100);
apple.y = (Math.random()*400+100);
apple.name = "apple" + n;
apples.push(apple.name);
existingApples++;
trace(existingApples);
trace(apples);
}
}
}
}
Apple.as:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.events.*;
import flash.display.*;
public class Apple extends MovieClip{
public function Apple() {
}
public function onMouseDown(e:MouseEvent):void{
this.startDrag();
}
public function onMouseUp(e:MouseEvent):void{
this.stopDrag();
}
}
}

Here is come commented example:
package
{
import flash.display.Scene;
import flash.display.Sprite;
import flash.events.MouseEvent;
public class Main extends Sprite
{
public function Main():void {
var apples:Array = new Array() ; // Declare and array
for (var i:int = 0 ; i < 10 ; i++) { //Let's make 10 apples
var apple:Apple = new Apple() ; //Create an apple
apple.x = Math.ceil(Math.random() * stage.stageWidth) ; //Assign random x
apple.y = Math.ceil(Math.random() * stage.stageHeight) ; //Assign random y
stage.addChild(apple) ; //Add it to stage, so we can see them
apples.push(apple) ; //Push into array
}
//EDITED
var draggableApple:Apple = apples[0] ;
draggableApple.addEventListener(MouseEvent.MOUSE_DOWN, draggableApple.onMouseDown) ;
draggableApple.addEventListener(MouseEvent.MOUSE_UP, draggableApple.onMouseUp) ;
}
}
}
And Apple.as
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Apple extends MovieClip {
public function Apple() {
this.graphics.lineStyle(2) ;
this.graphics.beginFill(0x00FF40) ;
this.graphics.drawCircle(0, 0, 20) ;
this.graphics.endFill() ;
//addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown) ;
//addEventListener(MouseEvent.MOUSE_UP, onMouseUp) ;
}
public function onMouseDown(event:MouseEvent):void {
this.startDrag() ;
}
public function onMouseUp(event:MouseEvent):void {
this.stopDrag() ;
}
}
}
Also, name of all variables must start with a small letter. myVariable
Names of classes must implement CamelCaseClass
Names of constants contain only big letters and underscores. MY_CONSTANT

Related

Score not displaying in AS3

I've got this code that mostly works. I know the ammo is being tracked correctly because I have it to be game over when the ammo runs out. My problem is that neither the score nor the remaining ammo are displaying. I'm not sure what I'm missing. Here's the code that I have relating to the issue.
package {
import flash.display.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.TextField;
import flash.media.Sound;
import flash.media.SoundChannel;
public class AirRaid extends MovieClip {
private var aagun:AAGun;
private var airplanes:Array;
private var bullets:Array;
public var leftArrow, rightArrow:Boolean;
private var nextPlane:Timer;
private var shotsLeft:int;
private var shotsHit:int;
public function startAirRaid () {
// init score
shotsLeft = 20;
shotsHit = 0;
showGameScore();
}
public function checkForHits (event:Event) {
for(var bulletNum:int = bullets.length - 1; bulletNum >= 0; bulletNum--) {
for (var airplaneNum:int = airplanes.length - 1; airplaneNum >= 0; airplaneNum-- ) {
if ( bullets[bulletNum].hitTestObject(airplanes[airplaneNum])) {
airplanes[airplaneNum].planeHit();
bullets[bulletNum].deleteBullet();
shotsHit++;
showGameScore();
break;
}
}
if ((shotsLeft == 0) && (bullets.length == 0)) {
endGame();
}
}
}
public function fireBullet() {
if (shotsLeft <= 0) return;
var b:Bullet = new Bullet(aagun.x, aagun.y, -300);
addChild(b);
bullets.push(b);
shotsLeft--;
showGameScore();
}
public function showGameScore() {
showScore.text = String("Score: " + shotsHit);
showShots.text = String("Shots Left: " + shotsLeft);
}
}
}
Please check if Font Embedding property on both showScore and showShots text fields are true (checked) in GUI editor in your project. If either text field is not added in GUI, use the approach in this question AS3 - TextField: Embedded font to start embedding fonts, or set a proper defaultTextFormat to either text field somewhere at initialization.

My AS3 game won't go to full screen

I'm making an AS3 platform game. I don't know why but it won't go to full screen...
Here's my code :
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
import flash.display.StageScaleMode;
import flash.events.MouseEvent;
public class PlatformGame extends MovieClip {
// movement constants
static const gravity:Number = .004;
// screen constants
static const edgeDistance:Number = 100;
// object arrays
private var fixedObjects:Array;
private var otherObjects:Array;
// hero and enemies
private var hero:Object;
private var enemies:Array;
// game state
private var playerObjects:Array;
private var gameScore:int;
private var gameMode:String = "start";
private var playerLives:int;
private var lastTime:Number = 0;
// start game
public function startPlatformGame() {
addEventListener(Event.ADDED_TO_STAGE, startGame);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
playerObjects = new Array();
gameScore = 0;
gameMode = "play";
playerLives = 3;
}
Do you know what could be the problem ? (I've just put the begining if my code, if you think it's necessary that I put all my code, don't hesitate to tell me)
Read this Adobe documentation:
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS2E9C7F3B-6A7C-4c5d-8ADD-5B23446FBEEB.html

How to apply a Glow Filter onto all the display objects in a movieclip in AS3?

I have a movieclip in which i have applied a FlashEff2 component for creating an effect on a text field.
But that FlashEff2 component discards all the Flash IDE Filters (GlowFilter). So what i am thinking now is to add a GlowFilter when FlashEff2 component ends its animation stuff.
But the problem is FlashEff2 breaks apart all the text into single letter which results in lots of instances.
So, how can i put this Glow Filter to all the instances inside the movieclip txt_mc on stage?
Thanks!
package
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.filters.BitmapFilter;
import flash.filters.GlowFilter;
import flash.text.TextField;
[SWF(width="500", height="100")]
public class TestEffects extends Sprite
{
private var _letters : Vector.<TextField> = new Vector.<TextField>;
public function TestEffects()
{
super();
// Add some text
var txt_mc : MovieClip = new MovieClip;
for(var i : uint = 0; i < 100; ++i)
{
var l : TextField = new TextField;
l.text = String.fromCharCode( Math.random() * 500 );
l.x = i * 10;
l.y = Math.random() * stage.stageHeight;
txt_mc.addChild( l );
_letters.push(l)
}
addChild(txt_mc);
// Apply a filter on every children
var effect : GlowFilter = new GlowFilter;
applyFilterChildren(txt_mc, effect);
// Just for fun
addEventListener(Event.ENTER_FRAME, updatePosition);
}
public function applyFilterChildren(t : DisplayObjectContainer, effect : BitmapFilter) : void
{
if(!t)
return;
for(var index : uint = 0; index < t.numChildren; ++index)
{
var child : DisplayObject = t.getChildAt( index );
child.filters = [ effect ];
}
}
// Update y position
protected function updatePosition(event:Event):void
{
for each(var l : TextField in _letters)
l.y = (l.y + 1) % 80;
}
}
}
Why don't you just add the GlowFilter to the container?
var glowFilter:GlowFilter = new GlowFilter();
txt_mc.filters = [glowFilter];

Object class rotating wrongly when it's called in movieclip class (My Arcade Game)

i have Cannon's class and it can rotate towards player !!
package com.musuh {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.sampler.NewObjectSample;
import com.ply.Heli;
public class Cannon extends MovieClip {
public var enTarget:Heli;
public function Cannon(enTarget:Heli) {
this.enTarget = enTarget;
addEventListener(Event.ENTER_FRAME , update);
}
public function fire (m:MouseEvent){
trace("fire");
}
function update (e:Event) {
if (parent != null) {
var dx = enTarget.x - x ;
var dy = enTarget.y - y ;
var angle = Math.atan2(dy,dx)/Math.PI*180-90;
rotation = angle;
}
}
}
}
when i called it to main class , it works fine (it can rotating towards player ) !!! , but when i called it inside Boss class (because in my game this boss can have at least 3 cannon ),it wasn't error but rotate wrongly towards player .. Why is it like that ?
it's the Boss Class
package com.musuh {
import flash.display.MovieClip;
import flash.events.Event;
import flash.utils.getTimer;
import com.peluru.bossBullet;
import com.ply.Heli;
import com.musuh.Cannon;
public class Boss extends MovieClip {
private var speedX:int = 6;
private var dx:Number; // speed and direction
public var bossHP:Number=20;
private var gun:Cannon;
public var hits:Array;
public var target:Heli;
public function Boss(target:Heli) {
this.target = target;
bossBullets = new Array();
hits = new Array(hit1,hit2,hit3,hit4,hit5,hit6);
addEventListener(Event.ADDED_TO_STAGE , onAddedToStage);
addEventListener(Event.ENTER_FRAME, movePlane)
addEventListener(Event.ENTER_FRAME, update)
}
private function onAddedToStage(event:Event):void
{
gun = new Cannon(target);
gun.x = 0;
gun.y = 200;
// add cannon to the MC Pitboss
addChild(gun);
}
public function movePlane(e:Event){
// move plane
this.x +=speedX;
{
speedX *= -1;
}
if (this.x <= 20)
{
speedX *= -1;
}
}
}
}
and it's the SCREEN SHOOT
http://img268.imageshack.us/img268/9250/1p0a.jpg
can you post the code where you actually add the Boss object? it looks like your
Boss.scaleX = -1
that'd explain the flipped x axis
But without seeing the code where you add your boss to main, I can't be sure.

Dispatching event doesn't fire :(

package com.fladev.background
{
//import all classes
import caurina.transitions.Tweener;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.FullScreenEvent;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class MainClass extends Sprite
{
//create variables
private var loaderMenu:Loader;
private var loaderNames:Array = new Array ();
private var loaderContents:Array = new Array ();
private var loaderSlide:Loader;
private var swfDisplayObject:DisplayObject;
private var swfComObject:Object;
private var xmlLoader:URLLoader = new URLLoader();
private var xmlSlideLoader:URLLoader = new URLLoader();
public function MainClass()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE, stageResize);
xmlLoader.addEventListener(Event.COMPLETE, showXML);
xmlLoader.load(new URLRequest("navigation.xml"));
//xmlSlideLoader.addEventListener(Event.COMPLETE, showSlideXML);
//xmlSlideLoader.load(new URLRequest("slides.xml"));
}
function showXML(e:Event):void
{
XML.ignoreWhitespace = true;
var menuBtns:XML = new XML(e.target.data);
var i:Number = 0;
for ( i = 0; i < menuBtns.navItem.length(); i++ )
{
loaderMenu = new Loader();
loaderMenu.name = menuBtns.navItem[i].name ;
loaderMenu.load(new URLRequest(menuBtns.navItem[i].swfURL));
loaderMenu.contentLoaderInfo.addEventListener(Event.COMPLETE, createSwfObjects);
}
}
private function createSwfObjects(event:Event):void
{
var swfContent = event.currentTarget.content as MovieClip ;
var swfName = event.currentTarget.loader ;
navigationContainer.addChild(event.target.loader);
showImage(swfContent);
if ( swfName.name == 'topNavigation' )
{
swfContent.addEventListener("clickHandle",topNavigationClickHandler);
}
}
private function topNavigationClickHandler():void
{
trace('Back to root');
}
private function showImage(navigationItem):void
{
try
{
navigationItem.alpha = 0;
Tweener.addTween(navigationItem, { alpha:1, time:1, transition:"easeOutSine" } );
navigationItem.smoothing = true;
} catch (e:Error) { trace('Error no tweening'); };
stageResize();
}
private function stageResize(e:Event=null):void
{
var centerImages:Array = new Array ( contentContainer, navigationContainer, backgroundImage ) ;
backgroundImage.x = 0;
backgroundImage.y = 0;
backgroundImage.scaleX = backgroundImage.scaleY = 1;
if ((stage.stageHeight / stage.stageWidth) < backgroundImage.height / backgroundImage.width) {
backgroundImage.width = stage.stageWidth;
backgroundImage.scaleY = backgroundImage.scaleX;
} else {
backgroundImage.height = stage.stageHeight;
backgroundImage.scaleX = backgroundImage.scaleY;
}
for each ( var centered:MovieClip in centerImages )
{
centered.x = stage.stageWidth / 2 - centered.width / 2;
centered.y = stage.stageHeight / 2 - centered.height / 2;
}
}
}
}
This is my code for the main.as.
And here my code for my loaded SWF on the maintimeline.
addEventListener(Event.ADDED_TO_STAGE, init);
function init(event:Event):void
{
trace('try dispatch');
dispatchEvent(new Event("clickHandle",true));
}
Try dispatch works, but it does not get back to the main to fire up "Back to root".
Any idea?
thx!
As long as all movieclips dispatching events are added to the display list, this should work. This makes me think that perhaps the event listener being added is not working. Try adding a trace statement to the block of code as shown below:
if ( swfName.name == 'topNavigation' )
{
trace("adding listener");
swfContent.addEventListener("clickHandle",topNavigationClickHandler);
}
I expect that this if condition is failing, and thus your listener is never being created. Also, you need to add a function parameter to the callback method "topNavigationClickHandler" to accept the event as the callback parameter. You have not done this, and this is an error that would be thrown at runtime when the event was received and dispatched to the callback method. You havn't seen this yet because your listener has never had to invoke the callback. So you're gonna have to fix this code like so:
private function topNavigationClickHandler(e:Event):void
{
trace('Back to root');
}
Also I just want to add that your if condition on setting this listener seems a bit redundant, since you already know you are expecting the navigation swf, because you're explicitly loading it. Also I don't believe the name property would be set like this. Typically the name is only set inside the IDE before compilation, and if it isn't, it gets dynamically generated at runtime. What might be more useful is to check the URL of the loaded SWF to see if it contains "topNavigation" or whatever the swf name is. You can do this like so:
var swfUrl:String = myLoader.contentLoaderInfo.url;
if (swfUrl.search("topNavigation") != -1){
//Match found, add listener for navigation
}