AS3 Not Adding Sprite to MovieClip - actionscript-3

My code is simply looping through an xml file and creating 'pages' (which are later animated).
This has all worked fine but now I want to add a sprite over the entire contents of the page if the contents of the xml contain a URL.
At run-time I can see that the checks for the URL are being processed correctly and that the overlay is being generated, but I cannot "see" it on the page.
The following code is located in a for loop for every page in the xml file:
var page:Page = new Page(); //MovieClip in my library
// ... other stuff
var textMC:FadeText = new FadeText(xml); //load the text from the xml fragment for this page
//if the text contains a URL (using RegExp)
if(textMC.hasLink())
{
var button:Sprite = new Sprite();
button.graphics.beginFill(0x000000);
button.graphics.drawRect(0, 0, 1, 1);
button.name= textMC.getLink();
button.x = button.y = button.alpha = 0;
button.width = rectangle.width;
button.height = rectangle.height;
button.buttonMode = true;
button.addEventListener(MouseEvent.CLICK, goToUrl, false, 0, true);
page.addChildAt(button, page.numChildren);
}
//... more code - such as add page to stage.
From the console (using FireBug and FlashBug) the button is being created, but I cannot see it on screen so I am guessing the addChild bit is at fault.
What is wrong and how do I fix it?
[edit]
Having set the alpha to 1 I can see that the overlay IS being added to the page, but it is not changing my cursor or responding to mouse clicks.
I now believe it is something wrong with the XML. It is correctly parsed XML (otherwise FlashPlayer would throw exceptions in my face) and it appears that this code works on every page except the second. Further more, if the second page is set as visible (a flag in the XML determins if the page is created or not) then none of the other pages overlay works.

Sorry to necro this thread but one thing I can think of is that because you specify a z-position to place your page it might be that the z-position generated by (i+1) is not the next one in line. AS3 doesn't allow display-objects to be placed on 'layers' with empty 'layers' between them which was allowed in AS2.
My guess is that during the loop at one point or another the loop doesn't generate a page which leaves an empty layer. The reason why the stage.addChild(page) actually works is because it simply searches for the next empty layer in that stack because you don't specify it.

button.x = button.y = button.alpha = 0;
set alpha to 1
button.alpha = 1;
and check for rectangle.width , rectangle.height
last thing, check for textMC.hasLink() if its true or not. If its true, there is another problem with your code that is not related to this sample code.

Illogical answer:
Replaced stage.addChildAt(page,i+1); with stage.addChild(page);.
I was clutching at straws. Have spent FAR too long working on this blip, but it works! I don't know WHY it works, and at this point I don't care; IT WORKS!!! (sorry for the unprofessionalism however I have spent two and a half days working on this and have just got it working!)
If someone wants to explain why it works, feel free. I would VERY much prefer to learn why this occurs that struggle to work around it.

Related

Android ListView binding programmatically

There are many examples of doing this in axml, but I would like to have a complete binding using code behind. To be honest, I would like to have NO axml, but seems like creating all the controls programmatically is a nightmare.
I first tried the suggestions at:
MvxListView create binding for template layout from code
I have my list binding from code-behind, and I get six rows (so source binding is working); but the cells itself does not bind.
Then at the following url:
Odd issue with MvvmCross, MvxListViewItem on Android
Stuart has the following comment: Have looked through. In this case, I don't think you want to use DelayBind. DelayBind is used to delay the binding action until next time the DataContext is set. In Android's MvxAdapter/MvxListItemView case, the DataContext is passed in the ctor - so DataContext isn't set again until the cell is reused. (This is different to iOS MvxTableDataSource).
So in essence, the only example I see shows DelayBind, which shouldn't work.
Can someone please show me some examples... thanks in advance.
Added reply to Comments:
Cheesebaron, first of all, a huge thank you and respect for all your contributions;
Now, why not use axml? Well, as programmers, we all have our own preferences and way of doing stuff - I guess I am old school where we didn't have any gui designer (not really true).
Real reasons:
Common Style: I have a setup where Core has all the style details, including what all the colors would be. My idea is, each platform would get the style details from core and update accordingly. It's easy for me to create controls with the correct style this way.
Copy-Paste across platform (which then I can even have as linked files if I wanted). For example, I have a login screen with web-like verification, where a red error text appears under a control; overall on that screen I have around 10 items that needs binding. I have already got iOS version working - so starting on Droid, I copied the whole binding section from ios, and it worked perfectly. So, the whole binding, I can make it same across all platform... Any possible error in my way will stop at building, which I think is a major advantage over axml binding. Even the control creation is extremely similar, where I have helpers with same method name.
Ofcourse I understand all the additional layout that has to be handled; to be honest, it's not that bad if one really think it through; I have created a StackPanel for Droid which is based on WP - that internally handles all the layouts for child views; so for LinearLayout, all I do is setup some custom parameters, and let my panel deal with it. Relative is a different story; so far, I have only one screen that's relative, and I can even make it Linear to reduce my additional layout code.
So, from my humble point of view, for my style, code-behind creation allows me to completely copy all my bindings (I do have some custom binding factories to allow that), copy all my control create lines; then only adding those controls to the view is the only part that is different (then again, droid and WP are almost identical). So there is no way I can miss something on one platform and all are forced to be the same. It also allows me to change all the styles for every platform just by changing the core. Finally, any binding error is detected during compile - and I love that.
My original question wasn't about NOT using axml... it was on how to use MvxListView where all the binding is done in code-behind; as I have explained, I got the list binding, but not the item/cell binding working.
Thanks again in advance.
Here is part of my LoginScreen from droid; I think it's acceptable amount of code for being without axml file.
//======================================================================================================
// create and add all controls
//======================================================================================================
var usernameEntry = ControlHelper.GetUITextFieldCustom(this, "Username.", maxLength: 20);
var usernameError = AddErrorLabel<UserAuthorization, string>(vm => ViewModel.Authorization.Username);
var passwordEntry = ControlHelper.GetUITextFieldCustom(this, "Password.", maxLength: 40, secureTextEntry: true);
var passwordError = AddErrorLabel<UserAuthorization, string>(vm => ViewModel.Authorization.Password);
var loginButton = ControlHelper.GetUIButtonMain(this);
var rememberMe = new UISwitch(this);
var joinLink = ControlHelper.GetUIButtonHyperLink(this, textAlignment: UITextAlignment.Center);
var copyRightText = ControlHelper.GetUILabel(this, textAlignment: UITextAlignment.Center);
var copyRightSite = ControlHelper.GetUIButtonHyperLink(this, textAlignment: UITextAlignment.Center);
var layout = new StackPanel(this, Orientation.Vertical)
{
Spacing = 15,
SubViews = new View[]
{
ControlHelper.GetUIImageView(this, Resource.Drawable.logo),
usernameEntry,
usernameError,
passwordEntry,
passwordError,
loginButton,
rememberMe,
joinLink,
ControlHelper.GetSpacer(this, ViewGroup.LayoutParams.MatchParent, weight: 2),
copyRightText,
copyRightSite
}
};
I just came across a similar situation myself using Mvx4.
The first link you mentioned had it almost correct AND when you combine it from Staurts comment in the second link and just remove the surrounding DelayBind call, everything should work out ok -
public class CustomListItemView
: MvxListItemView
{
public MvxListItemView(Context context,
IMvxLayoutInflater layoutInflater,
object dataContext,
int templateId)
: base(context, layoutInflater, dataContext, templateId)
{
var control = this.FindViewById<TextView>(Resource.Id.list_complex_title);
var set = this.CreateBindingSet<CustomListViewItem, YourThing>();
set.Bind(control).To(vm => vm.Title);
set.Apply();
}
}
p.s. I have asked for an Edit to the original link to help others.

Issues correctly removing childs from flash

hey im having issues removing my enemy blocks. at the moment if i hit everyone of them everything is fine but when i avoid one i get an error message of
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at EnergyJump/onTick()
at flash.utils::Timer/flash.utils:Timer::_timerDispatch()
at flash.utils::Timer/flash.utils:Timer::tick()
here is my code i have:
public function onTick( timerEvent:TimerEvent ):void
{
//if ranrom number is than than i
if ( Math.random() < i )
{
//place block on stage at location X=550, Y=330
var randomX:Number = Math.random() * 550;
var newBlock:Blocks = new Blocks( 550, 335 );
army.push( newBlock );
addChild( newBlock );
//increase speed of spawn
i = i + 0.0001;
}
//move blocks in correct direction
for each ( var block:Blocks in army )
{
block.move();
//if block is hit then remove health and remove child object
if ( avatar.hitTestObject( block ) )
{
hp.checkHP(20);
army.splice(army.indexOf(block), 1);
removeChild( block );
}
}
}
can anyone help me, i dont really know what slice is to be honest or how to use it...
You should have a look at the documentation for Array.splice() here.
The first argument needs to be the index (0, 1, 2 etc.) of the item you want to remove, not the item itself. Flash is trying to read block as an integer, but it defaults to 0, so instead of removing the block that has been hit it's just removing the first block in the list. Try this instead:
army.splice(army.indexOf(block), 1);
I assume you have some code which is clearing any remaining blocks in the list at the end of the game, but because the wrong blocks are being removed from the list it's trying to remove some that were actually hit already.
Are you sure there is a corresponding addChild() call for each of those objects that has been made before the call to removeChild()? There's not enough code being shown, at the moment, to be able to really tell what's going on, but also make sure removeChild() isn't being called more than once on the same object without addChild() being called in between each time.
Okay, I had a quick look through your files. It's getting a bit off topic for this question, but I'll list the problems I found. In general though you need to look at the parts Flash is complaining about and make sure you're really working with the right variables (eg. if you write block, try to make sure you know which block Flash is going to look at, and remember that the order matters when you change things.)
It's easy to accidentally remove the wrong items or try to use things that are null, so check each line and think about what each variable actually is at that point (maybe try tracing the variables out too).
In avatarEnterFrame you're checking for blocks that have gone off the side of the screen, but you haven't added a for each loop like in onTick, so when you use block there Flash is looking at your main public var block:Blocks; instead of the blocks in army.
In onPowerTick you need to adjust your splice in the same way as before, so that you remove the powerups object you're checking instead of the item at 0.
In restartGame you're setting gameOverScreen to null just before trying to remove it, so Flash doesn't know what to remove. Make sure you leave setting it to null until you're done with everything else.
I'll post a separate answer for your game over screen problem so that it's in the right place.

AS3 Loader doesn't unload after game reset

you have always been of great help for me throughout the last few years.
I could always find a solution to my programming problem.
This time however I couldn't find a solution to this one.
Although there are a few topics which discuss Loaders. Mine is a lot different.
The problem:
In the first game screen I load a movie (a movie converted to .swf).
And after I switch to the next state, it unloads and doesn't display any more.
At the end of the game I execute my own made reset function (which has not much to do
with the loader whatsoever, it just resets some static variables) and the game switches
to the first state.
The Loader once again shows up. But now when I switch states, the Loader is still displaying.
Note: I am using the flixel library. Although I don't think it makes a big difference in this case (though I figure it problably does since I still have the problem :P).
I have only placed the important code. I have three buttons. Let's say I push. the third button. In the switch case I enter case 2.
The reset function is a flixel function: FlxG.resetGame() but I figure it doesn't really
matter.
I hope this is enough information for someone to see the problem/solution.
Thanks in advance.
Here's the code:
AMCInlog.as
private var my_loader:Loader;
private var my_player:Object;
public function AMCInlog()
{
imgBackground = new FlxSprite(0, 0, Resources.imgStartMenuBackground);
add(imgBackground);
my_loader = new Loader();
my_loader.x = 40;
my_loader.y = 156;
my_loader.scaleX = 1.2;
my_loader.scaleY = 1.2;
//loadUserData();
moviePlayerSequence();
//userData.clear();
//createButtons();
}
private function moviePlayerSequence():void {
var request:URLRequest = new URLRequest("DGAME Movie.swf");
my_loader.load(request);
FlxG.stage.addChild(my_loader);
}
private function currentButtonFunction():void {
switch(currentButton) {
case 0:
my_loader.unloadAndStop();
FlxG.stage.removeChild(my_loader);
FlxG.switchState(new AMCRegister());
break;
case 1:
my_loader.unloadAndStop();
FlxG.stage.removeChild(my_loader);
FlxG.switchState(new AMCExistingAccountLogin());
break;
case 2:
my_loader.unloadAndStop();
FlxG.stage.removeChild(my_loader);
FlxG.switchState(new AMCPreferences());
break;
default:
break;
}
}
You never reset your loader, hence it just holds onto what it loaded last time, either simply try and reset (or re-initiate actually) your loader like so (not the best method (will go into flash garbage-collection which has never been that awesome) but hey, it works)
my_loader = new Loader();
Or (since i dont see it) try using simply unload(); instead of unloadAndStop(); (since well, you dont need to stop it, if you unload it properly, its gone anyway)
Good luck!

Flash AS3 typewriter with some extra effects

I'm trying to recreate the effect seen on this page: http://flupie.net/blog/2010/12/typewriter-effect-with-textanim-as3/ (example #2)
But without all the separate files.
The reason why I dont just use that code, is because A) It uses text that's in a string, and I want to be able to apply the effect to textfields. B) It uses separate .as files, and I want it all to be 1 file (I want to upload this on DeviantArt later, and as far as I know, you can only upload the .swf)
So is it possible to recreate that matrix style typewriter effect, without resorting to separate .as files and apply it to textfields? I'm really more of a designer than a programmer, so this is just a little too much for me.
EDIT: To get some more clarification on what I intend to achieve. I want to build a character sheet for a fictional character (think: name, appearance, background, etc) and since this character is in the future, I want to give it a futuresque feeling. So the end result will contain several separate textfields and possibly some images. All these textfields should "run" at the same time. Perhaps I'll also add some more "pages" but I'm assuming this is done by just adding another frame to the timeline and a button to link to it.
I'm currently trying to decipher the code linked above, since that is precisely what I'm aiming to achieve, font and glow effects included.
I've written a class (just for you! - but it's quite simple and I'm bored...) which you can use to achieve this effect. Obviously, it's in your interest to take a look at this code at some point, but I'll show you how to use it - and it's very simple - without knowing how it works:
In flash, create a new ActionScript file, copy the code below into it and save it as TypeFX.as - in the SAME directory as your .fla project file:
package {
import flash.utils.Timer;
import flash.text.TextField;
import flash.events.TimerEvent;
public class TypeFX {
private var timer:Timer;
private var text:String;
private var pos:int = 0;
private var field:TextField;
public function TypeFX(field:TextField, speed:int = 200, text:String = null) {
// constructor code
this.field = field;
if(text != null)
{
this.text = text;
}
else
{
this.text = field.text;
}
field.text = '';
timer = new Timer(speed, this.text.length);
timer.addEventListener(TimerEvent.TIMER,update);
timer.addEventListener(TimerEvent.TIMER_COMPLETE,kill);
timer.start();
}
private function update(e:TimerEvent):void
{
pos++;
field.text = text.substr(0,pos);
}
private function kill(e:TimerEvent):void
{
timer.removeEventListener(TimerEvent.TIMER,update);
timer.removeEventListener(TimerEvent.TIMER_COMPLETE,kill);
timer.stop();
timer = null;
text = null;
field = null;
}
}
}
Again, you don't need to understand that to use it, but it's quite simple when broken down, you might enjoy looking at how it works.
Now, take a TextField you want to apply a typewriter effect to - make sure it's set as 'Dynamic Text' and give it an instance name. For example's sake, let's call it myField - now, open the Actions panel. You can apply this effect in a couple of ways:
If you want to create a typewriter effect with the text which is already in the field (it'll clear it, then type it out), add the following code to the actions panel:
new TypeFX(myField);
This will type out the text which was present in the field with a 200ms interval between letters - if you want to change this interval, add a second argument:
new TypeFX(myField,500);
This increases the delay to 500ms
You can also send a string to type out, as opposed to using the text already in the field (this is recommended, it'll be easier to read later, trust me!):
new TypeFX(myField, 500, "The text to type into the field");
Just note that if you are using this method (passing a string) you need to specify a time (eg 500 above), you can't leave it blank like you can if you're just using the field text.
Hope this helps, let me know if you get stuck!

AS3 Flip effect leaving a trail?

I'm trying to create something with a flip effect tutorial from tutplus - http://active.tutsplus.com/tutorials/effects/iphone-page-transition-flash/
However my flip area is much bigger than the tutorial, it's 900px wide. Everything works fine except that it leaves a trail when the width is that big. You'll see it when you flip it a few times.
Someone else posted the same problem in the comments from last year, but no one replied.
Does anyone know a solution to this?
Edit:
Here is a screen shot: http://imageshack.us/f/823/unled2lo.jpg/ (click to enlarge)
The front is purple and the back is white.
As you can see it left a bit of the purple as the page flipped to white.
I couldn't get a screen shot of it turning, but it's even more obvious as the page is actually flipping because the width become narrow which reveals a whole lot more that's left behind on the page.
The tutorial you are using create the flip effect using the build in flash tween classes, they are absolute rubbish, and very slow if you compare to other third part tween classes. That may be causing the trail! Lee Brimelow has a great video tutorial about how to do exact what you need: http://gotoandlearn.com/play.php?id=91 he is using caurina, but I highly recommend you to replace it with tweenLight so far the best tween I ever used.
Ok, thats the walkthrough:
1- Download the files from Lee Brimelow tutorial here http://gotoandlearn.com/files/3dflip.zip
2- Download tweenLight AS3 classes here: http://www.greensock.com/tweenlite/
3- copy the com folder inside greensock-as3 and past it inside 3dflip folder. Now you have all the tween classes you need for your flip!
4- open the flash file 3dflip.fla and replace the original code (located in the first frame) with this:
import com.greensock.TweenLite;
import fl.video.*;
con.visible = false;
var flv:FLVPlayback = con.vid.flvp;
flv.addEventListener(VideoEvent.PLAYING_STATE_ENTERED, onStart);
function onStart(e:Event):void
{
con.visible = true;
loading.visible = false;
}
con.vid.spin.addEventListener(MouseEvent.CLICK, cl);
con.tclip.spin.addEventListener(MouseEvent.CLICK, cl);
var isTurning:Boolean = false;
function cl(e:Event):void
{
if(!isTurning)
{
TweenLite.to(con, 1, {rotationY:con.rotationY+180, onComplete:function(){isTurning=false;}});
isTurning = true;
}
}
addEventListener(Event.ENTER_FRAME, loop);
function loop(e:Event):void
{
if(con.rotationY > 90 && con.rotationY < 270)
con.addChild(con.tclip);
else
con.addChild(con.vid);
if(con.rotationY >= 360) con.rotationY = 0;
}
Thats it. Now publish and see the result. Now all you have to do is replace the video player with the content that you want!
I would check the state of first side - it seems that it's forgotten on stage when "the other side" kicks in.