AS3 : Load image from xml - actionscript-3

I try to load images from xml.
My script is on frame 1.
var fichierXML:URLRequest = new URLRequest("datas.xml");
//Chargement du fichier
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onLoaded);
loader.load(fichierXML);
//Traitement des données
function onLoaded(e:Event):void
{
//Récupération des données du fichier XML
var xml:XML = new XML(e.target.data);
//Extraction des données généralistes
var Name:XMLList = xml.list.name;
var pictureProfilOriginal:XMLList = xml.list.pictureProfilOriginal;
var pictureProfil:XMLList = xml.list.pictureProfil;
var totalView:XMLList = xml.list.totalView;
var totalLoves:XMLList = xml.list.totalLoves;
loadImage(image01, "crop_image_1.jpg");
}
function loadImage(mc:MovieClip, urlReq:String):void {
var loader:Loader = new Loader();
mc.addChild(loader);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, doneLoad);
// start loading
loader.load(new URLRequest(urlReq));
}
function doneLoad(e:Event):void {
e.target.loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, doneLoad);
// smoothing the bitmap
var bit:Bitmap = e.target.content;
if(bit != null)
bit.smoothing = true;
}
When my clip "image01" is on frame 1, it load my image crop_image_1.jpg, but if my clip "image01" is on frame 2, i have this error :
TypeError: Error #1009: Il est impossible d'accéder à la propriété ou à la méthode d'une référence d'objet nul.
at Film_animation_fla::MainTimeline/loadImage() [Film_animation_fla.MainTimeline::frame1:68]
at Film_animation_fla::MainTimeline/onLoaded() [Film_animation_fla.MainTimeline::frame1:62]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
I begin with actionscript, maybe anyone have an idea to help me.
Thanks

Try not to use more than one frame if you can. The target movie clip being on frame 2 means that is does not exist when you are trying to add the child to it "mc.addChild(loader);".
If you really need two frames, extend the key frame of the image01 to start from frame 1, and if it's not empty hide the movie clip. You will have to show image01 again when you arrive at frame 2.

Related

ActionScript 3.0: Moving to another scene by clicking a button

I have created the first scene of my small project. Now I want to move to the second scene of the app. The start one is called startScene, the second one playScene. Here is the code of the class linked to the first scene:
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFieldAutoSize;
import flash.events.MouseEvent;
public class dragMain extends MovieClip {
public function dragMain() {
setWelcomeMessage();
drawArrow();
createStartButton();
}
// funzione per settare il messaggio di benvenuto
function setWelcomeMessage(): void {
// TextField contenete il messaggio di benvenuto
var welcomeMessage: TextField = new TextField();
// formattazione per il messaggio di benvenuto
var welcomeFormat: TextFormat = new TextFormat("Verdana", 40, 0xFF0000);
// imposto il testo da visualizzare
welcomeMessage.text = "Welcome, click the button to start playing";
//
welcomeMessage.autoSize = TextFieldAutoSize.LEFT;
// cerco di centrare il testo ad occhio nella schermata
welcomeMessage.x = 500;
// applico la formattazione al testo
welcomeMessage.setTextFormat(welcomeFormat);
// aggiungo il testo allo stage
addChild(welcomeMessage);
}
// funzione che disegnera' la freccia
function drawArrow(): void {
// Sprite che conterra' la freccia disegnata
var arrow: Sprite = new Sprite();
arrow.graphics.beginFill(0XFF0000);
arrow.graphics.moveTo(800, 100); //500,500 // 200,200
arrow.graphics.lineTo(1000, 100); //700,500 // 400,200
arrow.graphics.lineTo(1000, 550); //700,950 // 400,650
arrow.graphics.lineTo(1100, 550); //800,950 // 500,650
arrow.graphics.lineTo(900, 700); //600,1100// 300,800
arrow.graphics.lineTo(700, 550); //400,950 // 100,650
arrow.graphics.lineTo(800, 550); //500,950 // 200,650
arrow.graphics.lineTo(800, 100); //500,500 // 200,200
addChild(arrow);
}
// funzione per creare il bottone
function createStartButton(): void {
var button: Sprite = new Sprite();
button.graphics.beginFill(0xFF0000);
button.graphics.moveTo(700, 800);
button.graphics.lineTo(1100, 800);
button.graphics.lineTo(1100, 1000);
button.graphics.lineTo(700, 1000);
button.graphics.lineTo(700, 800);
var clickMeMessage: TextField = new TextField();
clickMeMessage.x = 855;
clickMeMessage.y = 865;
var welcomeFormat: TextFormat = new TextFormat("Verdana", 40, 0x000000);
// imposto il testo da visualizzare
clickMeMessage.text = "click me!";
//
clickMeMessage.autoSize = TextFieldAutoSize.CENTER;
// applico la formattazione al testo
clickMeMessage.setTextFormat(welcomeFormat);
addChild(button);
addChild(clickMeMessage);
button.addEventListener(MouseEvent.CLICK, onClick);
}
function onClick(evt: MouseEvent): void {
gotoAndPlay(1, "playWindow");
}
}
}
When I click the button that I created through code I'm always on the startScene and I can't move to the playScene. I have got a frame on startScene and a frame on playScene. What's the problem and how can I solve it? Thank you!
First things first.
You have done gotoAndPlay so it will keep iterating between all the scenes on frame 1
gotoAndStop(1,"playScene");
If you don't want all the stuffs you have added on start scene you should remove them or set their visibility to false because addchild adds the object to the stage
This is what i did.I made the following variables global
var welcomeMessage: TextField;
var button: Sprite;
var clickMeMessage: TextField;
var arrow: Sprite;
and changed the onclick function a bit
function onClick(evt: MouseEvent): void {
button.visible = false;
clickMeMessage.visible = false;
arrow.visible = false;
welcomeMessage.visible = false;
gotoAndStop(1, "playScene");
}
well i think this should work
Try gotoAndStop(1, "playWindow"); instead of gotoAndPlay(). I suspect you don't have a stop() on frame 1 of your playScene so Flash is continuing past that scene.

As3 collision test

Im doing a space invaders game in flash when i came to collisions i had a 1061 error possibly undefined hittestobject through a reference with a static type class....
How can i fix that? tried many ways can't get rid of that error
/* Código que pára a timeline na 1 frame para que o menu continue apresentado*/
stop();
/*Movimenta a nave fazendo a seguir os movimentos do rato e esconde o cursor do sistema operacional*/
stage.addChild(arma_tiro);
arma_tiro.mouseEnabled = false;
arma_tiro.addEventListener(Event.ENTER_FRAME, fl_CustomMouseCursor);
function fl_CustomMouseCursor(event:Event)
{
arma_tiro.x = stage.mouseX;
}
Mouse.hide();
/* Mouse Click Event
Clicking on the specified symbol instance executes a function in which you can add your own custom code.
Instructions:
1. Add your custom code on a new line after the line that says "// Start your custom code" below.
The code will execute when the symbol instance is clicked.
*/
stage.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler_3);
function fl_MouseClickHandler_3(event:MouseEvent):void
{
var bullet:bullet_ = new bullet_();
addChild(bullet);
bullet.x=arma_tiro.x;
bullet.y=arma_tiro.y;
bullet.addEventListener(Event.ENTER_FRAME, moverbala);
}
function moverbala(event:Event):void // função para mover a bala para cima */
{
event.target.y=event.target.y-20;
}
//stage.addEventListener(Event.ENTER_FRAME, Primeira);
setInterval(Primeira, 1000) ; //define intervalo de tempo entre as varias repetiçoes da funçao
function Primeira(){ //funçao de spawn de nave 1
var invader1:invader_1 = new invader_1();
addChild(invader1);
invader1.x=0;
invader1.y=15;
invader1.addEventListener(Event.ENTER_FRAME, mover1);
}
function mover1(event:Event):void // função para mover a nave para lado direito */
{
event.target.x+=10;
}
//Nave 2
setInterval(Segunda, 1000) ; //define intervalo de tempo entre as varias repetiçoes da funçao
function Segunda(){ //funçao de spawn de nave 1
var invader2:invader_2 = new invader_2();
addChild(invader2);
invader2.x=0;
invader2.y=45;
invader2.addEventListener(Event.ENTER_FRAME, mover2);
}
function mover2(event:Event):void // função para mover a nave para lado direito */
{
event.target.x+=10;
}
//Nave 3
setInterval(Terceira, 1000) ; //define intervalo de tempo entre as varias repetiçoes da funçao
function Terceira(){ //funçao de spawn de nave 1
var invader3:invader_3 = new invader_3();
addChild(invader3);
invader3.x=0;
invader3.y=85;
invader3.addEventListener(Event.ENTER_FRAME, mover3);
}
function mover3(event:Event):void // função para mover a nave para lado direito */
{
event.target.x+=10;
}
// error line
if (bullet_.hitTestObject(invader_1))
{
//Remove bullet and enemy
mcGameStage.removeChild(bullet_);
mcGameStage.removeChild(invader_1);
}
it seems that bullet_ is a class and not an instance so you cannon call hitTestObject on it.
maybe try replace bullet_ by bullet.
there are many solution to do that but the simplest for me would be to keep 2 array, one for the bullets, one for the enemies.
so add arrays:
// create the array for the bullets
bullets :Array = [];
// create the array for the enemies
enemies :Array = [];
add an onEnterFrame event listener to do the tests and the game logic on each frame:
addEventListener( Event.ENTER_FRAME, _gameLoop );
change your function to create bullets and enemies:
function fl_MouseClickHandler_3( event:MouseEvent ):void
{
// create the bullet
var bullet:bullet_ = new bullet_();
addChild(bullet);
bullet.x=arma_tiro.x;
bullet.y=arma_tiro.y;
// add the bullet to the bullets array
bullets.push( bullet );
}
function Primeira():void
{
var invader1:invader_1 = new invader_1();
addChild(invader1);
invader1.x=0;
invader1.y=15;
enemies.push( invader1 );
}
function Segunda():void
{
var invader2:invader_2 = new invader_2();
addChild(invader2);
invader2.x=0;
invader2.y=45;
enemies.push( invader2 );
}
function Terceira():void
{
var invader3:invader_3 = new invader_3();
addChild(invader3);
invader3.x=0;
invader3.y=85;
enemies.push( invader3 );
}
now create the game loop function:
function _gameLoop():void
{
var firstLoop:Boolean = true;
// loop to move/remove the bullets
for( var a:int = bullets.length-1; a>=0; a-- )
{
bullets[a].y -= 20;
// if the bullet is not on screen anymore, remove it from array
if( bullets[j].y < 0 )
{
removeChild( bullet[a] );
bullets.splice(a,1);
continue;
}
}
// loop enemies
for( var i:int = enemies.length-1; i>=0; i-- )
{
// move the enemy
enemies[i].x += 10;
// loop the bullets to see if on collide the enemy
for( var j:int = bullets.length-1; j>=0; j-- )
{
// test collision with the enemy
if( enemies[i].hitTestObject( bullets[j] )
{
// make your enemy dead
removeChild( enemies[i] );
// remove it from the array
enemies.splice(i,1);
}
}
}
}
Hope this could helps you

How to add a sprite to box2d body?

I fixed. Problem solved.
I'm new in as3 and box2D, so at least I'm learning. I have a problem to add my sprites(movieclip) to a dynamic body. The sprite appear but it give me an error and because of that all the game-prototype works bad. With the statics I don't have any problem. What can I do?
This is my code:
Before the code I set them as a variable:
private var player:b2Body;
private var mc_player:MovieClip;
Firstly the function of my dynamic body:
public function createPlayer(px:int, py:int):void
{
mc_player = new _pork();
addChild(mc_player);
var playerDef:b2BodyDef = new b2BodyDef();
playerDef.position.Set(px / worldScale, py / worldScale);
playerDef.type = b2Body.b2_dynamicBody;
var playerShape:b2PolygonShape = new b2PolygonShape();
playerShape.SetAsBox(25 / 2 / worldScale, 40 / 2 / worldScale);
var playerForce:b2FixtureDef = new b2FixtureDef();
playerForce.shape = playerShape;
player = world.CreateBody(playerDef);
player.CreateFixture(playerForce);
}
Then a function to add the mc(movieclip):
private function drawPlayer():void
{
mc_player.x = player.GetPosition().x * worldScale;
mc_player.y = player.GetPosition().y * worldScale;
}
And in the update I just call it:
private function update(e:Event):void
{
drawPlayer();
}
The other proprieties I added, like set forces and gravity, this is not the problem.
This are the part where I think is the problem...
The error in flash:
TypeError: Error #1009: No se puede acceder a una propiedad o a un
método de una referencia a un objeto nulo. at Main/drawPlayer() at
Main/update()
I don't have any idea how can I fix it
Any help, please..
Thx everyone!
Edit:
Solution:
Sorry everyone I fail in my code. The error was that I never said to the game call the player when it is in the stage(I means the in the level) and not in the menu...because of this I was calling the player before appear the player. Sorry about my mistake..
So is something like that to call the movieclip player:
private function update(e:Event):void
{
//Call movieclips
if (mc_player) {
drawPlayer(); }
}
When/how is update() getting called? Is it a matter that you've created the callback before the mc_player has been initialized?

AS3 Image Loader - It loads itself (the swf)

My LoaderInfo will return the swf itself rather than the image given via the FileReference and Loader. I had problems debugging it, as LoaderInfo.content returns [Object Main] (My document class). After investigation, I discovered LoaderInfo.content is a swf file, according to contentType.
The problem is, the file reference for the image is correct (It is an image, and it is not the swf).
My code:
private function onAction(e:MouseEvent){
if(e.currentTarget.name == 0){
myFileReference = new FileReference();
myFileReference.browse(getTypes());
myFileReference.addEventListener(Event.SELECT, loadedImage);
myFileReference.addEventListener(Event.COMPLETE, loadImage15);
}
}
private function loadedImage(e:Event){
var imgHolder:ImageHolder = Main.imageHolder;
while(imgHolder.numChildren > 0){
imgHolder.removeChild(imgHolder.getChildAt(0));
}
myFileReference.load();
}
private function loadImage15(e:Event){
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadImg2);
loader.loadBytes(myFileReference.data);
trace(myFileReference.type); // .JPG
}
private function loadImg2(e:Event){
var lInfo:LoaderInfo = (e.target as LoaderInfo); //e.target is indeed LoaderInfo
lInfo.removeEventListener(Event.COMPLETE, loadImg2);
trace(loaderInfo.contentType); //application/x-shockwave-flash
var newSprite:MovieClip = loaderInfo.content as MovieClip;
Main.imageHolde.addChild(newSprite); //Error as you can't addChild Main to Main
}
private function getTypes():Array {
return [new FileFilter("Images","*.jpg;*.jpeg;*.gif;*.png")];
}
EDIT
I originally had a very complicated answer - which was wrong...
You simply have an error in your program:
// here you reference the Loader's contentLoaderInfo
var lInfo:LoaderInfo = (e.target as LoaderInfo);
lInfo.removeEventListener(Event.COMPLETE, loadImg2);
// but from here on out, you reference your parent class' "loaderInfo" property!
trace(loaderInfo.contentType);
var newSprite:MovieClip = loaderInfo.content as MovieClip; // <- this is your Main class!
Main.imageHolde.addChild(newSprite); //Error as you can't addChild Main to Main
Change loaderInfo to lInfo, and you should be fine.
I ask about this issue before :
loading image by Loader.loadBytes(byteArray)
Noone knows :]
If You loadBytes of image with Loader , You will recive :
Loader.content is MovieClip
Loader.content.getChildAt(0) is Bitmap

Actionscript 3.0 Dragging Loader image but getting error that it can't be converted to a movieclip

I have a script that loads an external image into the stage(I have the addChild() script somewhere else) but I keep getting an error that says:
TypeError: Error #1034: Type Coercion failed: cannot convert
flash.display::Loader#b1b7101 to flash.display.MovieClip. at
project1_fla::MainTimeline/drag()
var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("http://i54.tinypic.com/anom5d.png"));
my_loader.addEventListener(MouseEvent.MOUSE_DOWN, drag);
function drag(event:MouseEvent):void{
var my_loader:MovieClip = MovieClip(event.target);
my_loader.startDrag()
my_loader.scaleX = my_loader.scaleY = .95;
What I do to make the image draggable?
*(The image is loaded when the swf starts but the image won't because I put the addChild() in a if() statement. Could it be that since the image isn't loaded, it can't be a movieclip?)
There are a couple of errors with the following line.
var my_loader:MovieClip = MovieClip(event.target);
Firstly , the event target is of type Loader so you won't be able to coerce it into a MovieClip. Secondly, you would typically do this type of coercion when loading a swf , but you're loading a png!
var container:Sprite = new Sprite();
addChild( container);
my_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadingComplete);
my_loader.load(new URLRequest("http://i54.tinypic.com/anom5d.png"));
function onLoadingComplete(event:Event):void
{
container.addChild( event.currentTarget.loader.content );
container.addEventListener(MouseEvent.MOUSE_DOWN, drag);
//remove the listener here
}
function drag(event:MouseEvent):void{
container.startDrag()
container.scaleX = 0.95;
container.scaleY = 0.95;
}
var my_loader:Loader = new Loader();
addChild(my_loader);
my_loader.addEventListener(MouseEvent.MOUSE_DOWN, drag);
my_loader.load(new URLRequest("http://i54.tinypic.com/anom5d.png"));
function drag(event:MouseEvent):void{
my_loader.startDrag()
my_loader.scaleX = 0.95;
my_loader.scaleY = 0.95;
}