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

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.

Related

Actionscript 3 drag and drop multiple objects to target with well done

The drag and drop works, however, I have no idea how to create an if statement that goes to the next scene when all movieclips have been placed on the target.
I've tried placing the instance names in an if statement with the hittestobject however, no luck.
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.display.MovieClip;
/* Touch and Drag Event
Allows the object to be moved by holding and dragging the object.
*/
var objectoriginalX:Number;
var objectoriginalY:Number;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
var lemons:Array = [lemon1_mc, lemon2_mc, lemon3_mc, lemon4_mc, lemon5_mc];
for each(var lemonMC:MovieClip in lemons)
{
lemonMC.buttonMode = true;
lemonMC.addEventListener(TouchEvent.TOUCH_BEGIN, pickobject);
lemonMC.addEventListener(TouchEvent.TOUCH_END, dropobject);
lemonMC.startX = lemonMC.x;
lemonMC.startY = lemonMC.y;
}
var fl_DragBounds:Rectangle = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
function pickobject(event:TouchEvent):void
{
event.target.startTouchDrag(event.touchPointID, false, fl_DragBounds);
event.target.parent.addChild(event.target);
objectoriginalX = event.target.x;
objectoriginalY = event.target.y;
}
function dropobject(event:TouchEvent):void
{
if(event.target.hitTestObject(target_mc)){
event.target.buttonMode = false;
event.target.x = target_mc.x;
event.target.y = target_mc.y;
event.target.visible = false;
} else {
event.target.x = event.target.startX;
event.target.y = event.target.startY;
event.target.buttonMode = true;
}
}
var melons:Array = [melon1_mc, melon2_mc, melon3_mc, melon4_mc, melon5_mc, melon6_mc, melon7_mc];
for each(var melonMC:MovieClip in melons)
{
melonMC.buttonMode = true;
melonMC.addEventListener(TouchEvent.TOUCH_BEGIN, pickobject2);
melonMC.addEventListener(TouchEvent.TOUCH_END, dropobject2);
melonMC.startX = melonMC.x;
melonMC.startY = melonMC.y;
}
var fl_DragBounds2:Rectangle = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
function pickobject2(event:TouchEvent):void
{
event.target.startTouchDrag(event.touchPointID, false, fl_DragBounds2);
event.target.parent.addChild(event.target);
objectoriginalX = event.target.x;
objectoriginalY = event.target.y;
}
function dropobject2(event:TouchEvent):void
{
if(event.target.hitTestObject(target_null)){
event.target.buttonMode = false;
event.target.x = target_mc.x;
event.target.y = target_mc.y;
event.target.visible = false;
} else {
event.target.x = event.target.startX;
event.target.y = event.target.startY;
event.target.buttonMode = true;
}
}
How about adding a counter that is equal to number of objects to drag, then every time you drop object (and detect if it was on target) you decrements the counter and at the end of the function you check if it's 0?
An easy way to do this would be to remove your lemons/melons from their arrays when they pass the hit test. Then check if each array is empty and continue to the next scene should that be the case.
You can actually reduce redundant code and use the same function (dropobject) for both lemons and melons.
function dropobject(event:TouchEvent):void {
//Figure out which array this belongs to (is it a lemon or a melon)
var array:Array; //the array the dropped item belongs to
var hitMC:MovieClip; //the hit object for the lemon or melon
if(lemons.indexOf(event.currentTarget) > -1){ //if the lemon array contains the currentTarget
array = lemons;
hitMC = target_mc;
}else{
array = melons;
hitMC = target_null;
}
if(event.currentTarget.hitTestObject(hitMC)){
event.currentTarget.buttonMode = false;
event.currentTarget.x = hitMC.x;
event.currentTarget.y = hitMC.y;
event.currentTarget.visible = false;
//remove the item from it's array
array.removeAt(array.indexOf(event.currentTarget));
//check if there are any items left
if(lemons.length < 1 && melons.length < 1){
//both arrays are empty, so move on
play(); //or however you want to move on
}
}
}
Getting more advanced, a better way to do this would be to make a base class for your lemons, melons and anything else you want to drag in the future. Then you can add the dragging functionality into that base class and add properties for the hit target and an event for when it's hit it's target. This would give you one code base that can be easily applied to any library object.

I am getting the error code "1180: Call to a possibly undefined method DirectBlock."

I am using this code and getting the Error Message "1180: Call to a possibly undefined method DirectBlock." At Source: "block = new DirectBlock(lvlArray[i],(i-row*22)*25,row*25);"
package{
import flash.display.MovieClip;
import flash.events.*;
public class EmptyBlock extends MovieClip{
private var _root:MovieClip;
public function EmptyBlock(){
this.addEventListener(Event.ADDED, beginClass);
this.addEventListener(Event.ENTER_FRAME, eFrameEvents);
}
private function beginClass(e:Event):void{
_root = MovieClip(root);
this.buttonMode = true;//make this act like a button
this.addEventListener(MouseEvent.MOUSE_OVER, thisMouseOver);
this.addEventListener(MouseEvent.MOUSE_OUT, thisMouseOut);
this.addEventListener(MouseEvent.CLICK, thisClick);
}
private function eFrameEvents(e:Event):void{
if(_root.gameOver){
this.removeEventListener(Event.ENTER_FRAME, eFrameEvents);
this.removeEventListener(MouseEvent.MOUSE_OVER, thisMouseOver);
this.removeEventListener(MouseEvent.MOUSE_OUT, thisMouseOut);
this.removeEventListener(MouseEvent.CLICK, thisClick);
MovieClip(this.parent).removeChild(this);
}
}
private function thisMouseOver(e:MouseEvent):void{
this.graphics.drawRect(0,0,25,25);
this.graphics.endFill();
}
private function thisMouseOut(e:MouseEvent):void{
this.graphics.beginFill(0x333333);
this.graphics.drawRect(0,0,25,25);
this.graphics.endFill();
}
private function thisClick(e:MouseEvent):void{
}
}
}
And this is the .fla file:
stop();
//setting vars to step in for turns and special blocks
var S:String = 'START';
var F:String = 'FINISH';
var U:String = 'UP';
var R:String = 'RIGHT';
var D:String = 'DOWN';
var L:String = 'LEFT';
var startDir:String;
var finDir:String;
var startCoord:int;
var lvlArray:Array = new Array();
lvlArray = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,R,1,1,D,0,0,R,1,1,D,0,0,R,1,1,D,0,0,
0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,
0,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,
S,D,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,R,1,F,
0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,
0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,
0,R,1,1,U,0,0,R,1,1,U,0,0,R,1,1,U,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
];
//the names of these variables explain what they do
var currentLvl:int = 1;
var gameOver:Boolean = false;
function startGame():void{
//right now we don't have any code
}
var roadHolder:Sprite = new Sprite();
addChild(roadHolder);
function makeRoad():void{
var row:int = 0;
var block;//this will act as the block that we're placing down
for(var i:int=0;i<lvlArray.length;i++){//creating a loop that'll go through the level array
if(lvlArray[i] == 0){//if the current index is set to 0
block = new EmptyBlock();//create a gray empty block
block.graphics.beginFill(0x333333);
block.graphics.drawRect(0,0,25,25);
block.graphics.endFill();
addChild(block);
//and set the coordinates to be relative to the place in the array
block.x= (i-row*22)*25;
block.y = row*25;
} else if(lvlArray[i] == 1){//if there is supposed to be a row
//just add a box that will be a darker color and won't have any actions
block = new Shape();
block.graphics.beginFill(0x111111);
block.graphics.drawRect(0,0,25,25);
block.graphics.endFill();
block.x= (i-row*22)*25;
block.y = row*25;
roadHolder.addChild(block);//add it to the roadHolder
} else if(lvlArray[i] is String){block
//then create a special block
block = new DirectBlock(lvlArray[i],(i-row*22)*25,row*25);
addChild(block);
}
for(var c:int = 1;c<=16;c++){
if(i == c*22-1){
//if 22 columns have gone by, then we move onto the next row
row++;
}
}
}
}
//run these functions at the start
makeRoad();
startGame();
Off course, you got no class called DirectBlock and your class EmptyBlock has no parameters in the constructor (in case you wanted to use the second class and not the first).

AS3: Issues with multiple save/load slots

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");
}
}
}
}

#2007: Parameter format must be non-null?

i have a problem with my as3 code,
i try to link a movie clip to different scene (quiz scene).
so,i have 2 quiz in total, first quiz is using external script (as)
And the second quiz have the same script like first quiz, but i placed the action script inside fla. and it had different xml.
but then this error message appeared:
TypeError: Error #2007: Parameter format must be non-null.
at flash.text::TextField/set defaultTextFormat()
at hiragana/createText()[E:\flash\!!!! FLASH JADI\PAK ASHAR FIX\hiragana.as:80]
at hiragana/kuisdua()[hiragana::frame209:48]
at hiragana/frame209()[hiragana::frame209:249]
this is the code:
// creates a text field
public function createText(text:String, tf:TextFormat, s:Sprite, x,y: Number, width:Number): TextField {
var tField:TextField = new TextField();
tField.x = x;
tField.y = y;
tField.width = width;
tField.defaultTextFormat = tf; //looks like this is the source of problem (-.-)
tField.selectable = false;
tField.multiline = true;
tField.wordWrap = true;
if (tf.align == "left") {
tField.autoSize = TextFieldAutoSize.LEFT;
} else {
tField.autoSize = TextFieldAutoSize.CENTER;
}
tField.text = text;
s.addChild(tField);
return tField;
}
and this is the ettire code
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.net.URLLoader;
import flash.net.URLRequest;
///*public class*/ kuisduaa extends MovieClip {
// question data
/*private*/ var dataXML2:XML;
// text formats
/*private*/ var questionFormat2:TextFormat;
/*private*/ var answerFormat2:TextFormat;
/*private*/ var scoreFormat2:TextFormat;
// text fields
/*private*/ var messageField2:TextField;
/*private*/ var questionField2:TextField;
/*private*/ var scoreField2:TextField;
// sprites and objects
/*private*/ var gameSprite2:Sprite;
/*private*/ var questionSprite2:Sprite;
/*private*/ var answerSprites2:Sprite;
/*private*/ var gameButton2:GameButton;
// game state variables
/*private*/ var questionNum2:int;
/*private*/ var correctAnswer2:String;
/*private*/ var numQuestionsAsked2:int;
/*private*/ var numCorrect2:int;
/*private*/ var answers2:Array;
/*public*/ function kuisdua() {
// create game sprite
gameSprite2 = new Sprite();
addChild(gameSprite2);
// set text formats
questionFormat2 = new TextFormat("Arial",80,0xffffff,true,false,false,null,null,"center");
answerFormat2 = new TextFormat("Arial",50,0xffffff,true,false,false,null,null,"left");
scoreFormat2 = new TextFormat("Arial",30,0xffffff,true,false,false,null,null,"center");
// create score field and starting message text
scoreField2 = createText("",scoreFormat,gameSprite,-30,550,550);
messageField2 = createText("Loading Questions...",questionFormat,gameSprite,0,50,550);
// set up game state and load questions
questionNum2 = 0;
numQuestionsAsked2 = 0;
numCorrect2 = 0;
showGameScore2();
xmlImport2();
}
// start loading of questions
/*public*/ function xmlImport2() {
var xmlURL:URLRequest = new URLRequest("kuis2.xml");
var xmlLoader:URLLoader = new URLLoader(xmlURL);
xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
}
// questions loaded
/*public*/ function xmlLoaded2(event:Event) {
dataXML = XML(event.target.data);
gameSprite.removeChild(messageField);
messageField = createText("Tap Untuk Memulai",scoreFormat,gameSprite,-10,250,500);
showGameButton("mulai");
}
// creates a text field
/*public*/ function createText2(text:String, tf:TextFormat, s:Sprite, x,y: Number, width:Number): TextField {
var tField2:TextField = new TextField();
tField2.x = x;
tField2.y = y;
tField2.width = width;
tField2.defaultTextFormat = tf;
tField2.selectable = false;
tField2.multiline = true;
tField2.wordWrap = true;
if (tf.align == "left") {
tField2.autoSize = TextFieldAutoSize.LEFT;
} else {
tField2.autoSize = TextFieldAutoSize.CENTER;
}
tField2.text = text;
s.addChild(tField2);
return tField2;
}
// updates the score
/*public*/ function showGameScore2() {
scoreField2.text = "Soal: "+numQuestionsAsked2+" Benar: "+numCorrect2;
}
// ask player if they are ready for next question
/*public*/ function showGameButton2(buttonLabel:String) {
gameButton = new GameButton();
gameButton.label.text = buttonLabel;
gameButton.x = 240;
gameButton.y = 480;
gameSprite2.addChild(gameButton);
gameButton.addEventListener(MouseEvent.CLICK,pressedGameButton2);
}
// player is ready
/*public*/ function pressedGameButton2(event:MouseEvent) {
// clean up question
if (questionSprite2 != null) {
gameSprite2.removeChild(questionSprite2);
}
// remove button and message
gameSprite2.removeChild(gameButton);
gameSprite2.removeChild(messageField2);
// ask the next question
if (questionNum >= dataXML.child("*").length()) {
gotoAndStop(6);
} else {
askQuestion2();
}
}
// set up the question
/*public*/ function askQuestion2() {
// prepare new question sprite
questionSprite2 = new Sprite();
gameSprite2.addChild(questionSprite2);
// create text field for question
var question2:String = dataXML.item[questionNum].question2;
if (dataXML.item[questionNum].question.#type == "text") {
questionField2 = createText(question2,questionFormat2,questionSprite2,50,150,300);
} else {
var questionLoader2:Loader = new Loader();
var questionRequest2:URLRequest = new URLRequest("triviaimages/"+question2);
questionLoader2.load(questionRequest2);
questionLoader2.y = 150;
questionLoader2.x = 180;
questionSprite2.addChild(questionLoader2);
}
// create sprite for answers, get correct answer and shuffle all
correctAnswer2 = dataXML.item[questionNum2].answers.answer[0];
answers2 = shuffleAnswers(dataXML.item[questionNum2].answers);
// put each answer into a new sprite with a icon
answerSprites2 = new Sprite();
var xpos:int = 0;
var ypos:int = 0;
for(var i:int=0;i<answers2.length;i++) {
var answerSprite2:Sprite = new Sprite();
if (answers2[i].type == "text") {
var answerField2:TextField = createText(answers2[i].value,answerFormat2,answerSprite2,30,-35,200);
} else {
var answerLoader2:Loader = new Loader();
var answerRequest2:URLRequest = new URLRequest("triviaimages/"+answers2[i].value);
answerLoader2.load(answerRequest2);
answerLoader2.y = -22;
answerLoader2.x = 25;
answerSprite2.addChild(answerLoader2);
}
var letter:String = String.fromCharCode(65+i); // A-D
var circle:Circle = new Circle(); // from Library
circle.letter.text = letter;
circle.answer = answers[i].value;
answerSprite2.x = 100+xpos*250;
answerSprite2.y = 350+ypos*100;
xpos++
if (xpos > 1) {
xpos = 0;
ypos += 1;
}
answerSprite2.addChild(circle);
answerSprite2.addEventListener(MouseEvent.CLICK,clickAnswer); // make it a button
// set a larger click area
answerSprite2.graphics.beginFill(0x000000,0);
answerSprite2.graphics.drawRect(-50, 0, 200, 80);
answerSprites2.addChild(answerSprite2);
}
questionSprite2.addChild(answerSprites2);
}
// take all the answers and shuffle them into an array
/*public*/ function shuffleAnswers2(answers:XMLList) {
var shuffledAnswers2:Array = new Array();
while (answers2.child("*").length() > 0) {
var r:int = Math.floor(Math.random()*answers.child("*").length());
shuffledAnswers2.push({type: answers2.answer[r].#type, value: answers2.answer[r]});
delete answers2.answer[r];
}
return shuffledAnswers2;
}
// player selects an answer
/*public*/ function clickAnswer2(event:MouseEvent) {
// get selected answer text, and compare
var selectedAnswer2 = event.currentTarget.getChildAt(1).answer;
if (selectedAnswer2 == correctAnswer2) {
numCorrect++;
messageField2 = createText("Hai, kamu benar ! ",scoreFormat2,gameSprite2,-30,280,550);
} else {
messageField2 = createText("Iie, Jawabanmu Salah, yang benar adalah:",scoreFormat2,gameSprite2,53,280,370);
}
finishQuestion();
}
/*public*/ function finishQuestion2() {
// remove all but the correct answer
for(var i:int=0;i<4;i++) {
answerSprites2.getChildAt(i).removeEventListener(MouseEvent.CLICK,clickAnswer);
if (answers2[i].value != correctAnswer2) {
answerSprites2.getChildAt(i).visible = false;
} else {
answerSprites2.getChildAt(i).x = 200;
answerSprites2.getChildAt(i).y = 400;
}
}
// next question
questionNum2++;
numQuestionsAsked2++;
showGameScore2();
showGameButton2("Lanjutkan");
}
// clean up sprites
/*public*/ function CleanUp2() {
removeChild(gameSprite);
gameSprite2 = null;
questionSprite2 = null;
answerSprites2 = null;
dataXML2 = null;
}
the first quiz played perfectly with that code,
and i have no clue why this error appeared,
i'm beginner in as3 so i'm still lack in many ways,
can anyone help me,?
i really apreciate it.. :)
Are you sure that you're parsing a non-null TextFormat instance as the second argument of createText()?
The error means that you're supplying a null value for tf:TextFormat.
Unless I am missing something, your issue is here:
messageField2 = createText("Loading Questions...",questionFormat,gameSprite,0,50,550);
&
messageField = createText("Tap Untuk Memulai",scoreFormat,gameSprite,-10,250,500);
I see questionFormat2 and scoreFormat2 are instantiated, but I never see a questionFormat or scoreFormat. Your error says that the defaultTextFormat (or TextFormat supplied using setTextFormat(), for future reference), cannot be null. Null means that the object has not been instantiated/created yet. questionFormat and scoreFormat are never instantiated. Hell, their variables do not even exist. If you were using a proper development IDE (FlashBuilder, FlashDevelop, etc), you'd never be able to compile this code.
Switch those two lines to use the correct formats and you should be fine.

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();
}