AS3: Issues with multiple save/load slots - actionscript-3

I'm trying to take this very simple "game" and give it three save/load slots. Following a separate tutorial I can make it work with a single save slot but once I try adding more, it gives me the following error message.
1046:Type was not found or was not compile-time constant: save2.
1046:Type was not found or was not compile-time constant: save3.
I am new to actionscript 3 so I'm sure I'm being very newbish but I have tried to figure this out for quite some time now but just can't seem to. The whole thing is controlled by buttons already placed on the scene. I appreciate any help I can get.
The code:
import flash.net.SharedObject;
var saveDataObject:SharedObject;
var currentScore:Number = 0
init();
function init():void{
btnAdd.addEventListener(MouseEvent.CLICK, addScore);
btnSave1.addEventListener(MouseEvent.CLICK, save1);
btnSave1.addEventListener(MouseEvent.CLICK, saveData);
btnSave2.addEventListener(MouseEvent.CLICK, save2);
btnSave2.addEventListener(MouseEvent.CLICK, saveData);
btnSave3.addEventListener(MouseEvent.CLICK, save3);
btnSave3.addEventListener(MouseEvent.CLICK, saveData);
btnLoad1.addEventListener(MouseEvent.CLICK, save1);
btnLoad1.addEventListener(MouseEvent.CLICK, loadData);
btnLoad2.addEventListener(MouseEvent.CLICK, save2);
btnLoad2.addEventListener(MouseEvent.CLICK, loadData);
btnLoad3.addEventListener(MouseEvent.CLICK, save3);
btnLoad3.addEventListener(MouseEvent.CLICK, loadData);
}
function save1(e:MouseEvent):void{
saveDataObject = SharedObject.getLocal("savefile1");
}
function save2(e:MouseEvent):void{
saveDataObject = SharedObject.getLocal("savefile2");
}
function save3(e:MouseEvent):void{
saveDataObject = SharedObject.getLocal("savefile3");
}
function addScore(e:MouseEvent):void{
currentScore += 1;
updateScoreText();
}
function saveData(e:MouseEvent):void{
saveDataObject.data.savedScore = currentScore;
trace("Data Saved!");
saveDataObject.flush();
trace(saveDataObject.size);
}
function loadData(e:MouseEvent):void{
currentScore = saveDataObject.data.savedScore;
updateScoreText();
trace("Data Loaded!");
}
function updateScoreText():void
{
txtScore.text = ("Score: " + currentScore);
trace("Score text updated");
}

I tried your code and it works like a charm...
Anyways, I've made a simpler version that doesn't use so many functions and Events.
Here is a pure AS3 version of it (just save it as Test.as3 and use as Document Class in Flash), but you can copy the content of the Test() method and paste in a action frame.
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.SharedObject;
import flash.text.TextField;
public class Test extends Sprite
{
public function Test()
{
/***** START: Faking buttons and field *****/
var txtScore:TextField = new TextField();
addChild(txtScore);
var btnAdd:Sprite = new Sprite();
var btnSave1:Sprite = new Sprite();
var btnSave2:Sprite = new Sprite();
var btnSave3:Sprite = new Sprite();
var btnLoad1:Sprite = new Sprite();
var btnLoad2:Sprite = new Sprite();
var btnLoad3:Sprite = new Sprite();
var items:Array = [btnAdd, null, btnSave1, btnSave2, btnSave3, null, btnLoad1, btnLoad2, btnLoad3];
for (var i:int = 0; i < items.length; ++i)
{
var item:Sprite = items[i];
if (item)
{
item.graphics.beginFill(Math.random() * 0xFFFFFF);
item.graphics.drawRect(0, 0, 100, 25);
item.graphics.endFill();
item.x = 25;
item.y = i * 30 + 25;
addChild(item);
}
}
/***** END: Faking buttons and field *****/
var saveDataObject:SharedObject;
var currentScore:Number = 0
btnAdd.addEventListener(MouseEvent.CLICK, addScore);
btnSave1.addEventListener(MouseEvent.CLICK, save);
btnSave2.addEventListener(MouseEvent.CLICK, save);
btnSave3.addEventListener(MouseEvent.CLICK, save);
btnLoad1.addEventListener(MouseEvent.CLICK, load);
btnLoad2.addEventListener(MouseEvent.CLICK, load);
btnLoad3.addEventListener(MouseEvent.CLICK, load);
function getLocal(target:Object):String
{
if (target == btnSave1 || target == btnLoad1)
{
return "savefile1";
}
else if (target == btnSave3 || target == btnLoad2)
{
return "savefile2";
}
else if (target == btnSave2 || target == btnLoad3)
{
return "savefile3";
}
}
function save(e:MouseEvent):void
{
var local:String = getLocal(e.target);
saveDataObject = SharedObject.getLocal(local);
saveDataObject.data.savedScore = currentScore;
trace("Data Saved!");
saveDataObject.flush();
trace(saveDataObject.size);
}
function load(e:MouseEvent):void
{
var local:String = getLocal(e.target);
saveDataObject = SharedObject.getLocal(local);
currentScore = saveDataObject.data.savedScore;
updateScoreText();
trace("Data Loaded!");
}
function addScore(e:MouseEvent):void
{
currentScore += 1;
updateScoreText();
}
function updateScoreText():void
{
txtScore.text = ("Score: " + currentScore);
trace("Score text updated");
}
}
}
}

Related

flash action-script 3 save and load

Hey Guys I'm working on a game on flash action script 3 and i reached with my code to the point that i have already added a mute button which works perfectly but what i want to do is to keep it muted while in the game even if i closed the game re open it.
one another thing is that i want the game to be saved even if i closed it and re opened it exactly the way i left it.
so please help me guys here is my code below
var foundObjects:Number=0
var triesNumber:Number=0
stop()
import flash.net.SharedObject;
var mySo:SharedObject = SharedObject.getLocal("squaresGame");
if(mySo.data.levelNumber==null)
mySo.data.levelNumber="0.01"
//mySo.data.levelNumber
var level:Number=mySo.data.levelNumber
var sTransform1:SoundTransform = new SoundTransform(1,0);
function setMute1(vol){
sTransform1.volume = vol;
SoundMixer.soundTransform = sTransform1;
}
levelText.text=(level*100).toString()
var turkeyArray:Array = new Array();
turkeyArray[1] = m1;
turkeyArray[2] = m2;
turkeyArray[3] = m3;
turkeyArray[4] = m4;
turkeyArray[5] = m5;
turkeyArray[6] = m6;
turkeyArray[7] = m7;
turkeyArray[8] = m8;
turkeyArray[9] = m9;
m1.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m2.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m3.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m4.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m5.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m6.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m7.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m8.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m9.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
function fl_MouseClickHandler(event:MouseEvent):void
{
event.currentTarget.play()
testFoundObject(event.currentTarget)
}
function testFoundObject(mc:Object):void
{
if(mc.hitTestObject(apple1) || mc.hitTestObject(apple2)||mc.hitTestObject(apple3))
{
foundObjects++
applesquresound.play()
}
else
emptysquresound.play()
trace(foundObjects)
triesNumber++
if(triesNumber>=3)
if(foundObjects>=3)
{
level+=0.01
mySo.data.levelNumber=level.toFixed(2)
levelText.text=(level*100).toString()
yes.play()
}
else{
no.play()
}
}
addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);
function fl_EnterFrameHandler(event:Event):void
{
if(m1.alpha<1)
for(var counter:Number=1;counter<=9;counter++){
MovieClip(turkeyArray[counter]).alpha+=level
}
}
button_1.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler_2);
function fl_MouseClickHandler_2(event:MouseEvent):void
{
gotoAndPlay(1)
}
toggleMuteBtn.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler_3);
function fl_MouseClickHandler_3(event:MouseEvent):void
{
if(Mute1 == false) {
Mute1 = true;
setMute1(1);
toggleMuteBtn.gotoAndStop(1)
} else {
Mute1 = false;
setMute1(0);
toggleMuteBtn.gotoAndStop(2)
}
}
var locationMC:MovieClip=MovieClip(turkeyArray[randomRange(1,9)]);
apple1.x=locationMC.x
apple1.y=locationMC.y
locationMC=MovieClip(turkeyArray[randomRange(1,9)]);
apple2.x=locationMC.x
apple2.y=locationMC.y
while(apple2.hitTestObject(apple1) || apple2.hitTestObject(apple3))
{locationMC=MovieClip(turkeyArray[randomRange(1,9)]);
apple2.x=locationMC.x
apple2.y=locationMC.y
}
locationMC=MovieClip(turkeyArray[randomRange(1,9)]);
apple3.x=locationMC.x
apple3.y=locationMC.y
while(apple3.hitTestObject(apple1) || apple3.hitTestObject(apple2))
{locationMC=MovieClip(turkeyArray[randomRange(1,9)]);
apple3.x=locationMC.x
apple3.y=locationMC.y
}
function randomRange(minNum:Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
You can use SharedObject class to store and load information about sound muting. As I see in your code, you already using this class for storing levelNumber, so I believe its not a challenge for you.

Added child stays invisible even though its container is visible

I have been struggling for a couple of days with an issue in Flash CS4. I am re-structuring an old game project into a Main class which handles the mainMenu, playGame, etc. functions. I have a ship added from the "game", which is added by Main.
The issue is "myShip" works as expected, except it's never visible. I've checked a lot of times, and both myShip and its containter (game) visible properties are always true. Alpha values are not the problem either, nor layers nor depth. Every other child I've added from "game" works just fine, but "myShip" refuses to be visible.
Any ideas as to why this could happen? I do not know how what to try next to solve the problem. Any help would be very appreciated. The code for the Main, Game and Ship class is below.
Thank you!
Code from the Main class:
public class Main extends Sprite {
public var mainMenuDisplay:MainMenuDisplay;
public var game:Game;
public var gameOverMenu:GameOverMenu;
public function Main() {
showMainMenu();
}
public function showMainMenu() {
mainMenuDisplay = new MainMenuDisplay(this);
gameOverMenu=remove_movie_clip(gameOverMenu);
addChild(mainMenuDisplay);
}
public function showGameOver() {
gameOverMenu = new GameOverMenu(this);
game=remove_movie_clip(game);
addChild(gameOverMenu);
}
public function playTheGame() {
game = new Game(this);
mainMenuDisplay = remove_movie_clip(mainMenuDisplay);
gameOverMenu=remove_movie_clip(gameOverMenu);
stage.addChild(game);
}
private function remove_movie_clip(clip:*) {
if (clip) {
removeChild(clip);
}
return null;
}
}
Code from the Game class:
package {
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import com.coreyoneil.collision.CollisionList;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.events.MouseEvent;
import com.greensock.*;
import flash.display.Sprite;
import flash.display.SpreadMethod;
import flash.display.GradientType;
import flash.geom.Matrix;
import com.sounds.music.Music_mainMusic;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.DisplayObject;
public class Game extends MovieClip {
var mainClass:Main;
//Main menu
//var mainMenuDisplay:MainMenuDisplay = new MainMenuDisplay();
//static var inMenu:Boolean = true;
//
//Ship variables
static var myShip:Ship = new Ship();
var myDirectionBar:Direction_bar = new Direction_bar();
//
//Enemy variables
static var enemyShipTimer_1:Timer;
//
//PowerUp variables
static var powerUpTimer:Timer;
static var nuking:Boolean;
//
//Wall generation variables
static var wall_mov_speed:Number;
var randomize:Number = 1;
var wallArray:Array = new Array();
var index:int = 0;
//
//Wall collision variables (powered by CDK by Corey O'Neil)
var myWallCollisionList:CollisionList; // = new CollisionList(myShip);
var wall_collisions:Array = new Array();
//
//Score variables
static var score:Number;
static var scoreText:TextField = new TextField();
var scoreFormat = new TextFormat("LCD5x8H", 20, 0x0066FF, true);
var distance_score_counter:int;
//
//Health variables
static var healthMeter_1:HealthMeter = new HealthMeter();
//
//Game modes
//var levelSelectDisplay:LevelSelectDisplay = new LevelSelectDisplay();
//**NOTE: These are extremely important, because they are the functions, which in reality are attributes, that allow us to call,
//from an Event Listener, a function in which we have a parameter to pass. This way we call these variables instead of the
//function we are interested in, these will call it for us.
//var functionLevelSelect_1:Function = selectedLevel(1);
//var functionLevelSelect_2:Function = selectedLevel(2);
//var functionLevelSelect_3:Function = selectedLevel(3);
//var functionLevelSelect_4:Function = selectedLevel(4);
//var functionLevelSelect_5:Function = selectedLevel(5);
//The level composition (that's the numbers of the frame in the MC of the Walls, each number is a type. The last one stores all of them.
//var level_1_composition:Array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
//var level_2_composition:Array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
//var level_3_composition:Array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
//var level_4_composition:Array = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];
//var storyModeLevelCompositions:Array = new Array(level_1_composition, level_2_composition, level_3_composition, level_4_composition);
//
var levelPlaying:int = 0;
var wallPieceCount:int = 0;
//
//Pause variables
var pauseScreen:PauseScreen = new PauseScreen();
//This variables states whether we are in pause or not
static var isPause:Boolean = false;
//This other tells us if we can pause at the moment or not
static var isPauseable:Boolean = false;
//
//Game Over, new Game and Game menu variables
//static var gameOverMenu:GameOverMenu = new GameOverMenu();
static var inGameStopping:Boolean = false;
//
//Transition screen variables
var darkening:Boolean;
//NOTE: We do it this way because, when putting an Enter Frame event listener onto the function funcTransition,
//which has a pass variable, the variable changed all the time to true, giving us problems.
//Background graphics variables
var color1:uint = Math.floor(Math.random()*0xFFFFFF + 1);
var color2:uint = Math.floor(Math.random()*0xFFFFFF + 1);
var colors:Object = {left:color1, right:color2};
var newColor1:uint = Math.floor(Math.random()*0xFFFFFF + 1);
var newColor2:uint = Math.floor(Math.random()*0xFFFFFF + 1);
var newColors:Object = {left:newColor1, right:newColor2};
var mySprite:Sprite = new Sprite();
//
//Music variables
var myMainMusic:Music_mainMusic = new Music_mainMusic();
//
//Credits variables
//var myCredits:Credits = new Credits();
//var myVersion:VersionDisplay = new VersionDisplay();
//
//Other variables
//var initThingy:Boolean;
var initTransition:Boolean = true;
var allPurposeCounter:int = 0;
var myTransitionScreen:TransitionScreen = new TransitionScreen();
//
//New necessary variables
//
public function Game(passedClass:Main) {
mainClass = passedClass;
if (stage) {
init(null);
}else{
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
}
public function init(e:Event) {
this.removeEventListener(Event.ADDED_TO_STAGE, init);
this.parent.addChild(this);
//Necessary initial booting:
mySprite.x = 0;
mySprite.y = 0;
stage.addChildAt(mySprite, 1);
drawGradient();
animateBackground();
//////////////////////////////////////////////////////
/*mainMenuDisplay.x = 400 - mainMenuDisplay.width/2;
mainMenuDisplay.y = 240 - mainMenuDisplay.height/2;
stage.addChild(mainMenuDisplay);*/
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/*levelSelectDisplay.x = 400 - levelSelectDisplay.width/2;
levelSelectDisplay.y = 240 - levelSelectDisplay.height/2;
levelSelectDisplay.visible = false;
stage.addChild(levelSelectDisplay);*/
//////////////////////////////////////////////////////
//Transitions
myTransitionScreen.visible = false;
stage.addChild(myTransitionScreen);
//
//////////////////////////////////////////////////////
//myCredits.x = 20;
//myCredits.y = 438;
//stage.addChild(myCredits);
//myVersion.x = 710;
//myVersion.y = 438;
//stage.addChild(myVersion);
//////////////////////////////////////////////////////
//myMainMusic.play(0,99999);
initGame(null);
//mainMenuIdleState();
//
}
//////////////////////////////////////////////////////
/*function mainMenuIdleState(){
stage.addChild(mainMenuDisplay);
stage.addChild(levelSelectDisplay);
inMenu = true;
mainMenuDisplay.visible = true;
mainMenuDisplay.mainMenuPlayStoryButton_instance.addEventListener(MouseEvent.MOUSE_DOWN, level_select);
mainMenuDisplay.mainMenuPlayEndlessButton_instance.addEventListener(MouseEvent.MOUSE_DOWN, endless_mode_selected);
}*/
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/*function endless_mode_selected(e:Event){
levelPlaying = 0;
initGame(null);
}*/
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/*function level_select(e:Event){
mainMenuDisplay.visible = false;
levelSelectDisplay.visible = true;
levelSelectDisplay.levelSelectButton1_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_1);
levelSelectDisplay.levelSelectButton2_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_2);
levelSelectDisplay.levelSelectButton3_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_3);
levelSelectDisplay.levelSelectButton4_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_4);
levelSelectDisplay.levelSelectButtonBack_instance.addEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_5);
}
function selectedLevel(level:int):Function {
switch (level){
case 1:
return function(e:MouseEvent):void {
//trace("1 clicked");
levelPlaying = 1;
levelSelectDisplay.visible = false;
initGame(null);
}
break;
case 2:
return function(e:MouseEvent):void {
//trace("2 clicked");
levelPlaying = 2;
levelSelectDisplay.visible = false;
initGame(null);
}
break;
case 3:
return function(e:MouseEvent):void {
//trace("3 clicked");
levelPlaying = 3;
levelSelectDisplay.visible = false;
initGame(null);
}
break;
case 4:
return function(e:MouseEvent):void {
//trace("4 clicked");
levelPlaying = 4;
levelSelectDisplay.visible = false;
initGame(null);
}
break;
default:
return function(e:MouseEvent):void {
//trace("back clicked");
levelPlaying = 0;
levelSelectDisplay.visible = false;
mainMenuDisplay.visible = true;
levelSelectDisplay.levelSelectButton1_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_1);
levelSelectDisplay.levelSelectButton2_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_2);
levelSelectDisplay.levelSelectButton3_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_3);
levelSelectDisplay.levelSelectButton4_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_4);
levelSelectDisplay.levelSelectButtonBack_instance.removeEventListener(MouseEvent.MOUSE_DOWN, functionLevelSelect_5);
}
break;
}
}*/
//////////////////////////////////////////////////////
function initGame(e:Event):void{
//This has so many redundancies, when everything is done, START CLEANING THIS!
//////////////////////////////////////////////////////
//Main menu
//mainMenuDisplay.visible = false;
//inMenu = false; THIS GOES AT THE END TO PREVENT PROBLEMS
//directNewGame tells us if we come from the newGame function (and thus we do not go through the mainMenuIdleState
//function and this instances have not been placed on stage) or not. If we come from the main menu, we DO need to
//remove them.
//
trace(myShip);
//Ship
myShip.x = -10; //Before there were numbers to implement stage.stageWidth/2;
myShip.y = 200; //Before there were numbers to implement stage.stageHeight/2;
myShip.visible = true;
//mainClass.addChild(myShip);
this.addChild(myShip);
//We make sure the ship doesn't enter to stage with 0 health
//(problems of working with only one instance of ship due to the static var references)
Ship.health = 100;
//Check "NOTE" below
myShip.alpha = 0.35;
myShip.visible = true;
//
trace(myShip.visible);
//Direction bar
myDirectionBar.x = stage.stageWidth/2;
myDirectionBar.y = stage.stageHeight/2;
this.addChild(myDirectionBar);
//
//Timers (enemies)
enemyShipTimer_1 = new Timer(1000)
enemyShipTimer_1.addEventListener(TimerEvent.TIMER, spawn_enemies);
enemyShipTimer_1.start();
//
//Timer (powerUps)
powerUpTimer = new Timer(10000);
powerUpTimer.addEventListener(TimerEvent.TIMER, spawn_powerUp);
powerUpTimer.start();
//
//PowerUps (other)
nuking = false;
//
myWallCollisionList = new CollisionList(myShip);
//Initial movement speed of the walls
wall_mov_speed = 8;
//Calling to the generating/adequating wallArray function
adequateArrayOfWalls(true);
wallArray[0].gotoAndStop(1);
wallArray[1].gotoAndStop(1);
myWallCollisionList.addItem(wallArray[0].theActualWall);
myWallCollisionList.addItem(wallArray[1].theActualWall);
//Collision managements
wall_collisions = 0 as Array;
//NOTE: Here we limit the alpha value to consider for collision just to make sure the game doesn't start with you killed, and that you are "invincible"
//for some time
myWallCollisionList.alphaThreshold = 0.95;
//
//Adding score format and text
scoreText.defaultTextFormat = scoreFormat;
scoreText.x = 700;
scoreText.y = 10;
score = 0;
scoreText.text = String(score);
stage.addChild(scoreText);
distance_score_counter = 0;
scoreText.visible = true;
//
//Adding health meter
healthMeter_1 = new HealthMeter();
healthMeter_1.x = 10;
healthMeter_1.y = 10;
stage.addChild(healthMeter_1);
//
//Adding the Pause screen & other pause variables
pauseScreen.x = 400 - pauseScreen.width/2;
pauseScreen.y = 240 - pauseScreen.height/2;
pauseScreen.visible = false;
stage.addChild(pauseScreen);
isPauseable = true;
//Adding a key managing event (for pausing, menu, etc.)
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyManaging);
//
/*//Adding a Game Over Menu
gameOverMenu = new GameOverMenu();
gameOverMenu.x = 400 - gameOverMenu.width/2;
gameOverMenu.y = 240 - gameOverMenu.height/2;
gameOverMenu.visible = false;
stage.addChild(gameOverMenu);
gameOverMenu.playAgainButton_instance.addEventListener(MouseEvent.MOUSE_DOWN, newGame);
gameOverMenu.backToMenuButton_instance.addEventListener(MouseEvent.MOUSE_DOWN, backToTheMenu);
//*/
//Shield
//
//Event listeners
addEventListener(Event.ENTER_FRAME, update_game);
//
//////////////////////////////////////////////////////
/*//Credits
myCredits.visible = false;
myVersion.visible = false;
//
initThingy = true;
inMenu = false;*/
//////////////////////////////////////////////////////
}
function update_game(e:Event){
myShip.visible = true;
//Look the adequate array function for more info. We are just moving the two pieces of the array on stage
wallArray[(index - 1)].x -= wall_mov_speed;
wallArray[index].x -= wall_mov_speed;
if(wallArray[index].x < 0){
spawn_wall_piece();
}
//
if(index == 5){
//We call this function for cleaning
adequateArrayOfWalls(false);
}
if(wall_mov_speed < 20){
wall_mov_speed += 0.003;
}
wall_collisions = myWallCollisionList.checkCollisions();
if(wall_collisions.length > 0){
trace("hit!");
if(myShip.visible == true){
//We only kill the ship if it's visible, if not, it means it is already dead
Ship.receiveDamage(Ship.max_health);
}
wall_collisions = 0 as Array;
}
if(distance_score_counter >= 10){
distance_score_counter = 0;
updateScore(1);
}
distance_score_counter++;
//NOTE2: We use this nuke variable in order not to make the "nuke()" function static, type in which we couldn't handle the stage property
//And we also make this variable false here so as to eliminate not only a single enemy but all on stage
Enemy1.enemies_1Nuked = false;
if(nuking == true){
Enemy1.enemies_1Nuked = true;
nuking = false;
}
//We put these all the time at the front so we can see them and the walls don't overpass them
scoreText.parent.setChildIndex(scoreText, scoreText.parent.numChildren - 1);
healthMeter_1.parent.setChildIndex(healthMeter_1, healthMeter_1.parent.numChildren - 1);
pauseScreen.parent.setChildIndex(pauseScreen, pauseScreen.parent.numChildren -1);
//gameOverMenu.parent.setChildIndex(gameOverMenu, gameOverMenu.parent.numChildren - 1);
var n:uint = stage.numChildren;
for(var i=0; i < n; i++){
if(stage.getChildAt(i) is Enemy1){
var anEnemy1:Enemy1 = Enemy1(stage.getChildAt(i));
anEnemy1.parent.setChildIndex(anEnemy1, anEnemy1.parent.numChildren -1);
}
else if(stage.getChildAt(i) is PowerUp){
var aPowerUp:PowerUp = PowerUp(stage.getChildAt(i));
aPowerUp.parent.setChildIndex(aPowerUp, aPowerUp.parent.numChildren -1);
}
}
//Done like this due to the impossibility of calling a function inside an static one (in this case, gameOver)
if(inGameStopping == true){
funcEasing();
}
//Probably not necessary later
//////////////////////////////////////////////////////
/*if(initThingy == true){
stage.focus = stage;
initThingy = false;
}*/
//////////////////////////////////////////////////////
}
function spawn_enemies(e:Event){
var myEnemy1:Enemy1 = new Enemy1();
stage.addChild(myEnemy1);
}
function spawn_wall_piece(){
index++;
wallArray[index].x = (wallArray[index - 1].x + wallArray[index - 1].width);
wallArray[index].y = 0;
stage.addChild(wallArray[index]);
myWallCollisionList.addItem(wallArray[index].theActualWall);
myWallCollisionList.removeItem(wallArray[index - 2].theActualWall);
stage.removeChild(wallArray[index - 2]);
}
function adequateArrayOfWalls(init:Boolean):void{
//This only executes if we are initialitizing the array
if(init == true){
for(index = 0; index < 10; index++){
var aWall:Walls = new Walls();
//We check if we got special blocks next (e.g. "ramp caves"). Then we only allow a certain type of blocks to come.
//If no special block is detected, then we just randomize the next one, except for those that are not allowed to
//show up unless a previous special one appeared.
if(randomize == 9 || randomize == 15){
randomize = 15 + Math.floor(Math.random()*1 + 1);
}else{
randomize = Math.floor(Math.random()*14 + 1);
}
aWall.gotoAndStop(randomize);
//TheActualWall is the raw shape of the wall, where the ship collides, and it is what we push into collisionList,
//but not into the wallArray which includes the Walls (comprised by graphics and actual walls)
aWall.theActualWall.gotoAndStop(randomize);
wallArray.push(aWall);
}
wallArray[0].gotoAndStop(1);
wallArray[0].theActualWall.gotoAndStop(1);
stage.addChild(wallArray[0]);
wallArray[1].x = 800;
wallArray[1].y = 0;
stage.addChild(wallArray[1]);
//if not, then we are just cleaning it and rearranging it so it doesn't grow bigger and bigger
}else{
for(var a:Number = 0; a < index - 1; a++){
wallArray.splice(0,1);
}
for(a = index - 1; a < (10-2); a++){
var aWall2:Walls = new Walls();
if(randomize == 9 || randomize == 15){
randomize = 15 + Math.floor(Math.random()*1 + 1);
}else{
randomize = Math.floor(Math.random()*14 + 1);
}
aWall2.gotoAndStop(randomize);
aWall2.theActualWall.gotoAndStop(randomize);
wallArray.push(aWall2);
}
}
//Then, either way, we tell index to be 1 since the reference in the function is [index - 1] and [index], so it starts with [0] and [1]
index = 1;
}
static function updateScore(points:Number){
score += points;
scoreText.text = score.toString();
}
static function resetScore(){
score = 0;
scoreText.text = score.toString();
}
function spawn_powerUp(e:Event){
var pU:PowerUp = new PowerUp();
stage.addChild(pU);
}
static function gameOver(){
wall_mov_speed = 8;
//gameOverMenu.end_game_score_display.text = score.toString();
//gameOverMenu.visible = true;
scoreText.visible = false;
enemyShipTimer_1.stop();
powerUpTimer.stop();
inGameStopping = true; //In game stopping only influentiates in the easing speed effect
isPauseable = false;
}
function funcEasing(){
if(wall_mov_speed >= 0.1){
wall_mov_speed /= 1.07;
}else{
wall_mov_speed = 0;
removeEventListener(Event.ENTER_FRAME, update_game);
initTransition = true;
darkening = true; //See notes on variable declaration.
funcTransition(null);
}
}
function funcTransition(e:Event){
if(initTransition == true){
myTransitionScreen.init(darkening);
myTransitionScreen.parent.setChildIndex(myTransitionScreen, stage.numChildren - 1);
myTransitionScreen.parent.addEventListener(Event.ENTER_FRAME, funcTransition);
initTransition = false;
allPurposeCounter = 0;
}
if((darkening == true && myTransitionScreen.alpha == 1) || (darkening == false && myTransitionScreen.alpha == 0)){
trace("fsdfa");
allPurposeCounter++;
trace(allPurposeCounter);
if(allPurposeCounter >= 20){
myTransitionScreen.parent.removeEventListener(Event.ENTER_FRAME, funcTransition);
initTransition = true;
allPurposeCounter = 0;
if(darkening == true){ //This means if we are now with a black screen coming from the game, which is when we will end our game process
endGameProcess();
}
}
}
}
function endGameProcess(){
mainClass.showGameOver();
}
function newGame(e:Event){
darkening = true; //See notes on variable declaration.
initTransition = true;
funcTransition(null);
}
//Check To-Do List below
function funcPause(pMode:String){
if(pMode == "pausing"){
pauseScreen.visible = true;
removeEventListener(Event.ENTER_FRAME, update_game);
myShip.thePause("pausing");
//Check and stop the childs on stage (emitted by stage, so particles don't count)
var n:uint = stage.numChildren;
for(var i=0; i < n; i++){
if(stage.getChildAt(i) is Enemy1){
var anEnemy1:Enemy1 = Enemy1(stage.getChildAt(i));
anEnemy1.thePause("pausing");
}
else if(stage.getChildAt(i) is Trail){
var aTrailUnit:Trail = Trail(stage.getChildAt(i));
aTrailUnit.thePause("pausing");
}
else if(stage.getChildAt(i) is PowerUp){
var aPowerUp:PowerUp = PowerUp(stage.getChildAt(i));
aPowerUp.thePause("pausing");
}
}
enemyShipTimer_1.stop();
powerUpTimer.stop();
isPause = true;
isPauseable = false;
}else if(pMode == "unpausing"){
pauseScreen.visible = false;
addEventListener(Event.ENTER_FRAME, update_game);
myShip.thePause("unpausing");
//Check and re-run the childs on stage (emitted by stage, so particles don't count)
var m:uint = stage.numChildren;
for(var j=0; j < m; j++){
if(stage.getChildAt(j) is Enemy1){
var anotherEnemy1:Enemy1 = Enemy1(stage.getChildAt(j));
anotherEnemy1.thePause("unpausing");
}
else if(stage.getChildAt(j) is Trail){
var anotherTrailUnit:Trail = Trail(stage.getChildAt(j));
anotherTrailUnit.thePause("unpausing");
}
else if(stage.getChildAt(j) is PowerUp){
var anotherPowerUp:PowerUp = PowerUp(stage.getChildAt(j));
anotherPowerUp.thePause("unpausing");
}
}
enemyShipTimer_1.start();
powerUpTimer.start();
isPause = false;
isPauseable = true;
}
}
//Key pressing management
function keyManaging(e:KeyboardEvent){
var key:uint = e.keyCode;
trace("algo");
switch (key){
case Keyboard.P:
if(isPause == false && isPauseable == true){
funcPause("pausing");
}else if (isPause == true){
funcPause("unpausing");
}
break;
case Keyboard.M:
//go back to menu: still to complete
//Has to be only possible to do while in the pause menu
trace("going back to menu");
//
break;
}
}
//
//Background color management
function drawGradient():void {
var m:Matrix = new Matrix();
m.createGradientBox(805, 485, 0, 0, 0);
mySprite.graphics.clear(); // here we clean it
mySprite.graphics.beginGradientFill(GradientType.LINEAR, [colors.left, colors.right], [1, 1], [0x00, 0xFF], m, SpreadMethod.REFLECT);
mySprite.graphics.drawRoundRect(0,0,805,485, 0);
stage.setChildIndex(mySprite, 1);
}
function animateBackground(){
TweenMax.to(colors, 3, {hexColors:{left:newColor1, right:newColor2}, onUpdate:drawGradient, onComplete:reRandomize});
}
function reRandomize(){
color1 = newColor1;
color2 = newColor2;
newColor1 = Math.floor(Math.random()*0xFFFFFF + 1);
newColor2 = Math.floor(Math.random()*0xFFFFFF + 1);
animateBackground();
}
}
}
Code from Ship:
public class Ship extends MovieClip {
public function Ship() {
if (stage) {
init(null);
}else{
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
}
public function init(e:Event) {
this.removeEventListener(Event.ADDED_TO_STAGE, init);
this.addEventListener(Event.ENTER_FRAME, update_ship);
}
public function update_ship(e:Event){
x_vel = Direction_bar.dX*power;
y_vel = Direction_bar.dY*power;
this.x += x_vel;
this.y += y_vel;
if((10 < Math.abs(Direction_bar.dX) || 10 < Math.abs(Direction_bar.dY)) || ((0.9 < Math.abs(x_vel)||(0.9 < Math.abs(y_vel))))){
this.rotation = Direction_bar.point_direction;
}
rotation_now = this.rotation;
if(myShield != null){
if(myShield.visible == true){
myShield.alpha -= 0.0005;
if(myShield.alpha == 0){
myShield.visible = false;
myShield.alpha = 1;
}
}
}
}
Some basics that you have to know in order to understand what's going on.
It's a very common mistake to add things to stage.
Here's what the documentation of addChild says
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#addChild%28%29
objects should not be added to the Stage, directly, at all
I guess people add DispalyObjects to stage because they think it is
"the stage" that they see and interact with in the Flash authoring
environment. But it's not. stage.addChild() is not the same
thing as dragging a symbol from the library onto the screen. What by
default represents the main time line is the root property.
However, if you add anything to stage directly, its root property and its stage property both reference the same object,
which is regularly only referenced by stage. stage is some
container that your .swf is added to when running in the flash
player.
The documentation of addChildAt says this about the index:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObjectContainer.html#addChildAt%28%29
The child is added at the index position specified. An index of 0 represents the back (bottom) of the display list for this
DisplayObjectContainer object.
Applying these basics, the following happens:
FlashPlayer creates the stage object, instantiates your main class
and adds that instance to stage, it is the child with the index 0.
Among other things, stage.addChildAt(mySprite, 1); is executed,
adding mySprite as a second child to stage. With index of 1 it is
rendered in front of the object that is at index 0, which happens to
be the instance of your main class AKA your .swf file. I hope that
anything being rendered "outside the .swf file" illustrates well
enough why adding things to stage is not recommended.
Later, this.addChild(myShip); happens. (Which is actually the
proper way to do it; no need to use this here:addChild(myShip);
is all you need.) and adds the ship to the display list. Assuming all
of its parents are added to the display list as well, it will be
displayed.
But you still cannot see it, because you added mySprite in front of
the instance of your main class and filled it with a content in
drawGradient() which covers up everything else.
In all honesty, the best solution would be to start over from scratch.
Working with this code will not help you in any way. Even working yourself through it and making it work somehow will not make you understand anything better (except for how not to do things). It seems like the only motivation to modify this code to use classes was for the sake of doing it. Forcing such old code into the object oriented paradigm will not work very well. The benefits of oop will not be apparent, making this experience even more frustrating.
Last but not least, do not roll your own transition code. There are many libraries that do this (including flash's own Tween class http://www.republicofcode.com/tutorials/flash/as3tweenclass/ or the popular tweenlite http://greensock.com/tweenlite)
You could try adding an ADDED_TO_STAGE event. See this excellent explanation from the master of game programming
Understanding ADDED_TO_STAGE Event

Creating an ActionScript 3 RSS looping feed

I have the following AS3 code so far. What I need to do is have this code continually loop the feed it is consuming. Any solutions?
import flash.text.TextField;
import flash.text.TextFormat;
import flash.net.URLLoader;
import flash.events.IOErrorEvent;
//Read RSS feeds
var RSS_xmlData: XML = new XML();
var xmlLoader: URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, LoadXML);
xmlLoader.load(new URLRequest("http://www.oshawa.ca/news_rss.asp"));
function LoadXML(e:Event):void {
dtext.text="Loading...";
RSS_xmlData = new XML(e.target.data);
}
function pullFeed(rss: XML):void {
var str: String="";
str = rss.channel.item.title;
str = str.replace(/\s*\n/g," | ");
str = str.replace(/'/g,"\"");
//// shows specific entry
var items: Array = new Array();
items = str.split("|");
var tf: TextField = dtext;
var i:Number=0;
var myTimer:Timer = new Timer(4000,items.length);
myTimer.addEventListener(TimerEvent.TIMER, timerListener);
function timerListener (e:TimerEvent):void{
tf.text = items[i].toString();
scaleTextToFitInTextField(tf);
i++;
}
myTimer.start();
}
function scaleTextToFitInTextField(txt: TextField):void {
var f: TextFormat = txt.getTextFormat();
f.size = (txt.width > txt.height) ? txt.width : txt.height;
txt.setTextFormat(f);
while (txt.textWidth > txt.width - 4 || txt.textHeight > txt.height - 6) {
f.size = int(f.size) - 1;
txt.setTextFormat(f);
}
}
function onIOError(e:IOErrorEvent):void
{
trace(e.toString());
dtext.text="Finding Feed...";
}
I have tried a while loop, a for loop and a timer reset and restart but none appear to enable me to continually loop the feed.
Thanks
Reset your counter when you've finished iterating over your array:
function timerListener (e:TimerEvent):void{
tf.text = items[i].toString();
scaleTextToFitInTextField(tf);
// Reset counter to 0 when we've been all the way through the array
i = i < items.length - 1 ? i + 1 : 0;
}

Drag and Drop Game using AS3

import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
var wordArray:Array = [mc_clipA, mc_clipB];
var imgArray:Array = [Aimg, Bimg];
var posArray:Array = [ {x:816.15, y:396.05}, {x:518.3, y:410.05}];
var ClipA:MovieClip;
var ClipB:MovieClip;
var startXpositionClipA:Number;
var startYpositionClipA:Number;
var startXpositionClipB:Number;
var startYpositionClipB:Number;
wordArray[0].buttonMode = true;
wordArray[1].buttonMode = true;
wordArray[0].addEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDownClipA);
wordArray[1].addEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDownClipB);
//Mouse Down Function for ClipA
function item_onMouseDownClipA(event:MouseEvent):void {
ClipA = MovieClip(event.currentTarget);
startXpositionClipA = ClipA.x;
startYpositionClipA = ClipA.y;
addChild(ClipA);
ClipA.startDrag();
stage.addEventListener(MouseEvent.MOUSE_UP, stage_onMouseUpClipA);
wordArray[0].removeEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDownClipA);
wordArray[1].removeEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDownClipB);
}
//Mouse Up Function for ClipA
function stage_onMouseUpClipA(event:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_UP, stage_onMouseUpClipA);
ClipA.stopDrag();
var indexClipA:int = wordArray.indexOf(ClipClipA);
var matchClipClipA:MovieClip = MovieClip(imageArray[indexClipA]);
if(matchClipClipA.hitTestPoint(ClipA.x, ClipA.y, true)) {
ClipA.x = positionArray[indexClipA].x;
ClipA.y = positionArray[indexClipA].y;
ClipA.removeEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDownZip);
ClipA.buttonMode = false;
var tot=0;
tot=tot+10;
score.text="You scored: " + tot +" Points ";
var setTimer:Timer = new Timer(1000,60);
setTimer.addEventListener(TimerEvent.TIMER,doTask);
setTimer.start();
function doTask(event:TimerEvent) {
gotoAndStop(1,"Scene 2");
setTimer.stop();
}
}
else
{
ClipA.x = startXpositionClipA;
ClipA.y = startYpositionClipA;
wordArray[0].addEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDownClipA);
wordArray[1].addEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDownClipB);
}
}
//Mouse Down Function for ClipB
function item_onMouseDownClipB(event:MouseEvent):void {
ClipB = MovieClip(event.currentTarget);
startXpositionClipB = ClipB.x;
startYpositionClipB = ClipB.y;
addChild(ClipB);
ClipB.startDrag();
stage.addEventListener(MouseEvent.MOUSE_UP, stage_onMouseUpClipB);
wordArray[0].removeEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDownClipA);
wordArray[1].removeEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDownClipB);
}
//Mouse Up Function for ClipB
function stage_onMouseUpClipB(event:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_UP, stage_onMouseUpClipB);
ClipB.stopDrag();
var indexClipB:int = wordArray.indexOf(ClipB);
var matchClipClipB:MovieClip = MovieClip(imageArray[indexClipB]);
if(matchClipClipB.hitTestPoint(ClipB.x, ClipB.y, true)) {
ClipB.x = positionArray3[indexTie].x;
ClipB.y = positionArray3[indexTie].y;
ClipB.removeEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDownClipB);
ClipB.buttonMode = false;
var tot=0;
tot=tot;
score.text="You scored: " + tot +" Points ";
var setTimer:Timer = new Timer(1000,60);
setTimer.addEventListener(TimerEvent.TIMER,doTask);
setTimer.start();
function doTask(event:TimerEvent) {
gotoAndStop(1,"Scene 2");
setTimer.stop();
}
}
else
{
ClipB.x = startXpositionClipB;
ClipB.y = startYpositionClipB;
wordArray[0].addEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDownClipA);
wordArray[1].addEventListener(MouseEvent.MOUSE_DOWN, item_onMouseDownClipB);
}
}
This is regarding a drag n drop game. A particular object name will be displayed to the user then the user has to drag n drop the correct image to specified position and once the task is completed it will dynamically navigate to the next scene. For that i have used the timer class. I am getting this error in the scene 2 but in scene 1 the code runs perfectly.
The naming conventions are all correct but i still get the following error,
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at MethodInfo-1156()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
Can someone help me with this.
Your locally declared method "doTask" is removed right after the execution of the mouse listener. You should either create an anonymous inline listener
var setTimer:Timer = new Timer(1000,60);
setTimer.addEventListener(TimerEvent.TIMER, function(event:TimerEvent):void {
gotoAndStop(1,"Scene 2");
setTimer.stop();
});
setTimer.start();
Some like to do so but I am not a big fan of inline declaration. I would create a real method in my class as a listener.
private var setTimer:Timer;
function stage_onMouseUpClipB(event:MouseEvent):void {
...
setTimer = new Timer(1000,60);
setTimer.addEventListener(TimerEvent.TIMER,doTask);
...
}
function doTask(event:TimerEvent):void {
gotoAndStop(1,"Scene 2");
setTimer.stop();
}

How to load an external image on a drag & drop object using AS3?

NEW MESSAGE - THE SOLUTION I ENDED UP APPLYING
This is what I used to load an external image into a movie clip and drag and drop.
The feedback part is pretty much the same from the old code.
var holdermc_Arr:Array = new Array(4);
for(var i:uint = 0; i < holdermc_Arr.length; i++)
{
holdermc_Arr[i] = this["panel" + (i+1) + "_mc"];
var myLoader:Loader = new Loader();
var fileRequest:URLRequest = new URLRequest("images/" + (i+1) + ".jpg");
myLoader.load(fileRequest);
holdermc_Arr[i].addChild(myLoader);
holdermc_Arr[i].addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
holdermc_Arr[i].addEventListener(MouseEvent.MOUSE_UP, dropIt);
holdermc_Arr[i].buttonMode = true;
}
var startX:Number;
var startY:Number;
var counter:Number = 0;
function pickUp(event:MouseEvent):void {
startX = event.currentTarget.x;
startY = event.currentTarget.y;
setChildIndex(MovieClip(event.currentTarget),numChildren-1);
event.currentTarget.startDrag();
reply_txt.text = "";
}
OLD MESSAGE BELLOW
This is my latest attempt with the current error I am getting.
I actually would like to work with the code of my previous attempt because to me is easier that way to add multiple draggable movie clips.
But whichever the code, what seems to be the fundamental problem is that I am not setting up the property correctly for the "Loader".
Let me know if a link to the example is needed.
The error is the following:
ReferenceError: Error #1069: Property dropTarget not found on
flash.display.Loader and there is no default value. at
cs5test_fla::MainTimeline/ReleaseToDrop()
The code is the following
var myLoader:Loader = new Loader();
panel1_mc.addChild(myLoader);
var url:URLRequest = new URLRequest("uploadedImages/photo_1.jpeg");
myLoader.load(url);
var startX:Number;
var startY:Number;
var counter:Number = 0;
panel1_mc.addEventListener(MouseEvent.MOUSE_DOWN, ClickToDrag);
function ClickToDrag(event:MouseEvent):void
{
panel1_mc.startDrag();
startX = event.target.x;
startY = event.target.y;
reply_txt.text = "";
event.target.parent.addChild(event.target);
}
stage.addEventListener(MouseEvent.MOUSE_UP, ReleaseToDrop);
function ReleaseToDrop(event:MouseEvent):void
{
panel1_mc.stopDrag();
var myTargetName:String = "target" + event.target.name;
var myTarget:DisplayObject = getChildByName(myTargetName);
if (event.target.dropTarget != null && event.target.dropTarget.parent == myTarget){
reply_txt.text = "Good Job!";
event.target.x = myTarget.x;
event.target.y = myTarget.y;
event.target.removeEventListener(MouseEvent.MOUSE_DOWN, ClickToDrag);
event.target.removeEventListener(MouseEvent.MOUSE_UP, ReleaseToDrop);
event.target.buttonMode = false;
counter++;
} else {
reply_txt.text = "Try Again!";
event.target.x = startX;
event.target.y = startY;
}
if(counter == 1){
reply_txt.text = "Congrats, you're finished!";
}
}
OLDER MESSAGE BELLOW
I am still struggling.
I am new to all this so I am really tying the best I can to grasp it.
The ActionScript I am trying to work with is all the way at the bottom.
I'd really appreciate if someone tries to look at this code and tell me how can I load external images to each draggable movie clip with out getting the following error.
ReferenceError: Error #1069: Property startDrag not found on
flash.display.Loader and there is no default value. at
dragdropDilema_fla::MainTimeline/pickUp() ReferenceError: Error #1069:
Property stopDrag not found on flash.display.Loader and there is no
default value. at dragdropDilema_fla::MainTimeline/dropIt()
I tried to use a simple var loader but for what I can see on the error, I have to set up the startDrag property to work with the Loaded image and not with the draggable movie clips that are currently in place??
I thought I would have just been simple if I had use the following for each:
var myLoader:Loader = new Loader();
imageHolder.addChild(myLoader);
var url:URLRequest = new URLRequest("uploadedImages/photo_1.jpeg");
myLoader.load(url);
and then do something like:
square_mc.imageHolder.addChild(myLoader);
but when I do that I get the error anyway when I click on the image.
Here is the entire code: It is supposed to count when the object meet their target and gives a message all through out and at the end.
panel1_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
panel1_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
panel1_mc.buttonMode = true;
var startX:Number;
var startY:Number;
var counter:Number = 0;
function pickUp(event:MouseEvent):void {
startX = event.target.x;
startY = event.target.y;
event.target.startDrag(true);
reply_txt.text = "";
event.target.parent.addChild(event.target);
}
function dropIt(event:MouseEvent):void {
event.target.stopDrag();
var myTargetName:String = "target" + event.target.name;
var myTarget:DisplayObject = getChildByName(myTargetName);
if (event.target.dropTarget != null && event.target.dropTarget.parent == myTarget){
reply_txt.text = "Good Job!";
event.target.x = myTarget.x;
event.target.y = myTarget.y;
event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickUp);
event.target.removeEventListener(MouseEvent.MOUSE_UP, dropIt);
event.target.buttonMode = false;
counter++;
} else {
reply_txt.text = "Try Again!";
event.target.x = startX;
event.target.y = startY;
}
if(counter == 1){
reply_txt.text = "Congrats, you're finished!";
}
}
Thanks.
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLRequest;
var _dragMc:MovieClip = new MovieClip();
addChild(_dragMc);
loadImage("image.jpg")
function loadImage(path:String):void
{
var _loader:Loader = new Loader();
var _loaderToLoad:URLRequest = new URLRequest(path);
_loader.load(_loaderToLoad);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded, false, 0, true);
}
function imageLoaded(evt:Event):void
{
addLoader(evt.currentTarget.loader, _dragMc);
}
function addLoader(loader:Loader, container:DisplayObjectContainer):void
{
container.addChild(loader);
addListeners();
}
function addListeners():void
{
_dragMc.addEventListener(MouseEvent.MOUSE_DOWN, setDrag, false, 0, true);
}
function setDrag(evt:MouseEvent):void
{
_dragMc.addEventListener(MouseEvent.MOUSE_MOVE, doDrag, false, 0, true);
_dragMc.removeEventListener(MouseEvent.MOUSE_DOWN, setDrag);
}
function doDrag(evt:MouseEvent):void
{
_dragMc.startDrag(false, null);
stage.addEventListener(MouseEvent.MOUSE_UP, endDrag, false, 0, true);
_dragMc.removeEventListener(MouseEvent.MOUSE_MOVE, doDrag);
}
function endDrag(evt:MouseEvent):void
{
_dragMc.stopDrag();
_dragMc.addEventListener(MouseEvent.MOUSE_DOWN, setDrag, false, 0, true);
stage.removeEventListener(MouseEvent.MOUSE_UP, endDrag);
}
This loads an image onto a MovieClip called _dragMc. The rest from there is up to you. I also added some quick code that will enable you to drag _dragMc around.