Another strange thing when working with Flash's HTML5 Canvas is that variables cease to exist when you move to the next frame.
I am used to having a root timeline that I can store info on that all other movieclips might need, but this won't work if they disappear between one frame and the next.
My current adjustment is to move everything down by one timeline. So I have a single frame on the uppermost timeline, and the movie clip sitting on that contains several frames, as I would normally lay things out. If something needs to be stored while moving to the next frame, then I just store it on the parent timeline.
for this function that I wanted all movie clips to be able to access:
this.giveDimensions = function (mc) {
mc.height = mc.nominalBounds.height * mc.scaleY;
mc.width = mc.nominalBounds.width * mc.scaleX;
}
In the timeline of the movieclip:
this.parent.giveDimensions(this.work_btn);
A diary about programming problems - to help me more easily learn from (and Google) past mistakes.
Showing posts with label as3. Show all posts
Showing posts with label as3. Show all posts
Wednesday, 7 October 2015
Monday, 18 August 2014
How to randomly generate -1 or +1, in one line.
A hobby of mine is avoiding if statements, with mathematical formula that return the right number based on other conditions.
It is easy to generate a 0 or a 1 randomly, simply use Math.round(Math.random());
That will work in a number of languages, or something similar.
For a random -1 or +1, try this:
var randNum = -1 + (2*Math.round(Math.random));
If the random number generated by Math.random() is 0.5 or above, then the answer will be 1. If the random number generated is less than 0.5, the answer will be 1.
Enjoy!
It is easy to generate a 0 or a 1 randomly, simply use Math.round(Math.random());
That will work in a number of languages, or something similar.
For a random -1 or +1, try this:
var randNum = -1 + (2*Math.round(Math.random));
If the random number generated by Math.random() is 0.5 or above, then the answer will be 1. If the random number generated is less than 0.5, the answer will be 1.
Enjoy!
Tuesday, 22 July 2014
How to rewind an animation, AS3
To make the animation rewindable, it needs to be all on one timeline for starters. With no movieclips doing anything complicated that will look weird if everything is going backwards while they are going forwards. Flashing or jiggling, or something like that is fine, but it has to work backwards and forwards.
Graphic symbols are fine, because they will play backwards as the movie clip goes backwards.
Anyway...
In order to make the clip go backwards:
clip.addEventListener(Event.EnterFrame, goBack);
function goBack(evnt:Event):void {
clip.prevFrame();
}
In order to get the clip to stop going backwards, either once it gets to the beginning, or at certain points along the way, put code on the relevant frames inside the movie clip that checks if the eventListener exists, and if it does, removes it.
I hope that was clear enough.
Graphic symbols are fine, because they will play backwards as the movie clip goes backwards.
Anyway...
In order to make the clip go backwards:
clip.addEventListener(Event.EnterFrame, goBack);
function goBack(evnt:Event):void {
clip.prevFrame();
}
In order to get the clip to stop going backwards, either once it gets to the beginning, or at certain points along the way, put code on the relevant frames inside the movie clip that checks if the eventListener exists, and if it does, removes it.
I hope that was clear enough.
Friday, 13 September 2013
Tuesday, 10 September 2013
Easy - Get REAL Co-ordinates of a Movieclip Inside a Movieclip: localToGlobal, AS3
localToGlobal allows you to get the actual position of a movie clip, that is inside another movieclip.
Normally, if you trace, or try to get, the x or y coordinate of a movie clip, you will get its position, relative to the 0,0 coordinates of the movie clip it is sitting in. These are the local coordinates of the child movieclip.
To get the global coordinates, ie, where it REALLY is on the main stage, you need points, and the localToGlobal function.
e.g
(On the stage, there is a squareHole_mc, and inside that is a roundPeg_mc.)
var pt:Point = new Point(squareHole_mc.roundPeg_mc.x,squareHole_mc.roundPeg_mc.y);
pt = squareHole.localToGlobal(pt);
So basically, you create a Point, that contains the local x and y coordinates you are interested in. Then you use localToGlobal to find out the global version of those coordinates, bearing in mind they are sitting in a parent movieclip.
UPDATE:
Now in one line(!!!):
var pt:Point = sqH.localToGlobal(new Point(sqH.rPeg.x,sqH.rPeg.y));
Normally, if you trace, or try to get, the x or y coordinate of a movie clip, you will get its position, relative to the 0,0 coordinates of the movie clip it is sitting in. These are the local coordinates of the child movieclip.
To get the global coordinates, ie, where it REALLY is on the main stage, you need points, and the localToGlobal function.
e.g
(On the stage, there is a squareHole_mc, and inside that is a roundPeg_mc.)
var pt:Point = new Point(squareHole_mc.roundPeg_mc.x,squareHole_mc.roundPeg_mc.y);
pt = squareHole.localToGlobal(pt);
So basically, you create a Point, that contains the local x and y coordinates you are interested in. Then you use localToGlobal to find out the global version of those coordinates, bearing in mind they are sitting in a parent movieclip.
UPDATE:
Now in one line(!!!):
var pt:Point = sqH.localToGlobal(new Point(sqH.rPeg.x,sqH.rPeg.y));
Monday, 9 September 2013
Losing Focus on Textfield, AS3
I had a problem with a text field, I wanted to click on it, have something happen, and be able to continue typing straight away, but it kept losing focus after the first letter.
So I added a trace statement to find out what was happening, and then it would lose focus after it was clicked.
The reason was the trace statement was causing the whole swf to lose focus. So I am sending a trace statement in the frame, so that the initial focus is dealt with. The losing of focus doesn't occur after the first trace statement.
P.S. To set focus using action script:
stage.focus = textfield_txt;
textfield_txt.setSelection(textfield_txt.length,textfield_txt.length);
So I added a trace statement to find out what was happening, and then it would lose focus after it was clicked.
The reason was the trace statement was causing the whole swf to lose focus. So I am sending a trace statement in the frame, so that the initial focus is dealt with. The losing of focus doesn't occur after the first trace statement.
P.S. To set focus using action script:
stage.focus = textfield_txt;
textfield_txt.setSelection(textfield_txt.length,textfield_txt.length);
Friday, 6 August 2010
Line breaks
OK, so...
I am entering text in a flash text field, which gets sent to a mysql database. This later gets retrieved by php, and folded into a javascript function, so that another swf can use that data.
The problem is, if there are any line breaks in the initial text, then that ends up in the javascript function, and is seen as an error.
So to solve it, I will attempt to get the php file that takes the text out of the database, to convert that line break into something that the javascript function can stand, and that the swf can interpret.
Continuation -
Yeah, that worked. First I tried nl2br, which is supposed to put html linebreak tags where the line breaks are, although I din't see this effect. But this would have required me to make changes to my flash file.
So I used:
$lineBreaks = Array("\n","\r");
$iQuestion = ...get text from MySQL database
$oQuestion = str_replace($lineBreaks,'\u000d',$iQuestion);
$lineBreaks is an array of possible ways in which the line breaks may come down, I wasn't sure if this would differ depending on the user's operating system etc.
I am entering text in a flash text field, which gets sent to a mysql database. This later gets retrieved by php, and folded into a javascript function, so that another swf can use that data.
The problem is, if there are any line breaks in the initial text, then that ends up in the javascript function, and is seen as an error.
So to solve it, I will attempt to get the php file that takes the text out of the database, to convert that line break into something that the javascript function can stand, and that the swf can interpret.
Continuation -
Yeah, that worked. First I tried nl2br, which is supposed to put html linebreak tags where the line breaks are, although I din't see this effect. But this would have required me to make changes to my flash file.
So I used:
$lineBreaks = Array("\n","\r");
$iQuestion = ...get text from MySQL database
$oQuestion = str_replace($lineBreaks,'\u000d',$iQuestion);
$lineBreaks is an array of possible ways in which the line breaks may come down, I wasn't sure if this would differ depending on the user's operating system etc.
Labels:
as3,
Javascript,
line breaks,
mysql,
php,
str_replace
Monday, 12 July 2010
Sending/Loading... Something
I have to look this up every single time, so I thought I would put it somewhere easy to find:
function submitData() {
var nRequest:URLRequest = new URLRequest('backend.php');
nRequest.method = URLRequestMethod.POST;
var dataObj:URLVariables = new URLVariables();
dataObj.someInfo = 'some information';
nRequest.data = dataObj;
var loader:URLLoader = new URLLoader(nRequest);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, onComplete);
loader.load(nRequest);
}
function onComplete(evnt:Event) {
var rVariables:URLVariables = new URLVariables(evnt.target.data);
trace(rVariables.someReturnedValue);
}
So in summary,
URLLoader --> URLRequest --> URLVariables
function submitData() {
var nRequest:URLRequest = new URLRequest('backend.php');
nRequest.method = URLRequestMethod.POST;
var dataObj:URLVariables = new URLVariables();
dataObj.someInfo = 'some information';
nRequest.data = dataObj;
var loader:URLLoader = new URLLoader(nRequest);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, onComplete);
loader.load(nRequest);
}
function onComplete(evnt:Event) {
var rVariables:URLVariables = new URLVariables(evnt.target.data);
trace(rVariables.someReturnedValue);
}
So in summary,
URLLoader --> URLRequest --> URLVariables
Friday, 2 July 2010
Events and Priorities
Just a note for future reference:
I tried using the priority parameter of a MouseEvent listener, to make the listener on the root get called before the listener within the movie clip, but it wouldn't work.
It was, however, able to distinguish between two listeners on the root timeline...
I tried using the priority parameter of a MouseEvent listener, to make the listener on the root get called before the listener within the movie clip, but it wouldn't work.
It was, however, able to distinguish between two listeners on the root timeline...
Monday, 21 June 2010
Sorting by date
Hurrah!
My date sorting problem is finally solved. Simply format your date with the most important figures first, and with leading zeros. Then any ordinary sort (ie alphabetical) will return an array of these sorted by year, then month, etc.
eg. 4.15pm 23rd September 2009 => '2009-09-23-16-15'
PS. Actionscript 3 considers 09 to represent the month of October, because January is 0.
My date sorting problem is finally solved. Simply format your date with the most important figures first, and with leading zeros. Then any ordinary sort (ie alphabetical) will return an array of these sorted by year, then month, etc.
eg. 4.15pm 23rd September 2009 => '2009-09-23-16-15'
PS. Actionscript 3 considers 09 to represent the month of October, because January is 0.
Friday, 11 June 2010
Oh dear, oh dear ... oh dear.
Stung by the cache of loaded swfs... again.
Basically, the animation was getting hung up because it couldn't find the variables is was looking for - because instead of loading the updated swf - it was loading some outdated version that didn't have everything in it.
The way to avoid this, for testing purposes, is to attach a querystring with a random value - so that each time the swf is loaded, it is a different call, then the browser will look for the most recent file.
Stung by the cache of loaded swfs... again.
Basically, the animation was getting hung up because it couldn't find the variables is was looking for - because instead of loading the updated swf - it was loading some outdated version that didn't have everything in it.
The way to avoid this, for testing purposes, is to attach a querystring with a random value - so that each time the swf is loaded, it is a different call, then the browser will look for the most recent file.
Text won't load
I have decided to mention this before I figure out how to do it - thinking out loud, as it were, might help me to make sense of it.
So I am going to remove functionality step by step, until I track the source of the problem - I have an array that contains a list of all the text fields, and a pointer to what text it should be displaying, it works on the frames that aren't that complicated.
It also works on my test environment.
So first of all, I will switch off all the php/js type things in the swf, and see if it works then.
So I am going to remove functionality step by step, until I track the source of the problem - I have an array that contains a list of all the text fields, and a pointer to what text it should be displaying, it works on the frames that aren't that complicated.
It also works on my test environment.
So first of all, I will switch off all the php/js type things in the swf, and see if it works then.
Thursday, 10 June 2010
Array.filter
Using a helpful page by 'devon o wolfgang', I am using this:
var arr:Array = ['','later','what','','ok'];
trace(arr);
arr = arr.filter(removeBlankElements);
function removeBlankElements(element:*, index:uint, arr:Array):Boolean {
return element != '';
}
trace(arr);
to get rid of blank string elements in my arrays.
var arr:Array = ['','later','what','','ok'];
trace(arr);
arr = arr.filter(removeBlankElements);
function removeBlankElements(element:*, index:uint, arr:Array):Boolean {
return element != '';
}
trace(arr);
to get rid of blank string elements in my arrays.
Getting the String out of the Textfield
I had always thought, possibly due to the lack of autofill, that you couldn't do this:
trace(f.text.indexOf('h'));
but you can.
Oh well.
trace(f.text.indexOf('h'));
but you can.
Oh well.
Monday, 31 May 2010
TextLineMetrics...continued
This code works:
test_txt.addEventListener(Event.CHANGE,getLonger);
function getLonger(evnt:Event):void {
var met:TextLineMetrics = test_txt.getLineMetrics(0);
trace(met.height);
trace(met.ascent);
trace(met.descent);
trace(met.leading);
trace(' ');
if(test_txt.textHeight > test_txt.height){
test_txt.height = test_txt.textHeight + 6;
}
}
So, why would 6 be the magic number? I tried this in font size 18, 24, and 96, and different font faces as well. (By the way, in my previous efforts, the first line wasn't scrolling up because of using '+=', actually, it was because there wasn't enough added. So this can happen with '=' as well, if the textfield height isn't large enough.)
Anyway, if you have a look at this diagram:

(from http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/text/TextLineMetrics.html)
You can see a '2-pixel gutter' at the top and bottom of the text field, that gives 4 extra pixels, and there is the 'leading' value as well. I have traced out the 'leading' value in different faces and sizes, it is always 2.
So my theory is, that you need to take account of the gutters, and the leading for the next line. So for safety's sake, I will use '4 + met.leading';
UPDATE: You can set 'leading' in the properties panel, if you mouse over the second option in 'Spacing', it says 'Line spacing' - Mine was set to 2.0, but if I change it to, for example 5, the met.leading traces out 5.
test_txt.addEventListener(Event.CHANGE,getLonger);
function getLonger(evnt:Event):void {
var met:TextLineMetrics = test_txt.getLineMetrics(0);
trace(met.height);
trace(met.ascent);
trace(met.descent);
trace(met.leading);
trace(' ');
if(test_txt.textHeight > test_txt.height){
test_txt.height = test_txt.textHeight + 6;
}
}
So, why would 6 be the magic number? I tried this in font size 18, 24, and 96, and different font faces as well. (By the way, in my previous efforts, the first line wasn't scrolling up because of using '+=', actually, it was because there wasn't enough added. So this can happen with '=' as well, if the textfield height isn't large enough.)
Anyway, if you have a look at this diagram:

(from http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/text/TextLineMetrics.html)
You can see a '2-pixel gutter' at the top and bottom of the text field, that gives 4 extra pixels, and there is the 'leading' value as well. I have traced out the 'leading' value in different faces and sizes, it is always 2.
So my theory is, that you need to take account of the gutters, and the leading for the next line. So for safety's sake, I will use '4 + met.leading';
UPDATE: You can set 'leading' in the properties panel, if you mouse over the second option in 'Spacing', it says 'Line spacing' - Mine was set to 2.0, but if I change it to, for example 5, the met.leading traces out 5.
Sunday, 30 May 2010
TextLineMetrics...to be continued.
OK, I am currently trying to make a text box that grows in length when the typer makes extra lines.
I tried:
if(test_txt.textHeight > test_txt.height) {
test_txt.height = (test_txt.height /(test_txt.numLines - 1)) * test_txt.numLines;
}
but text fields have some extras around the edges and stuff, so the text box got too big as time went by.
As a sidenote, I would like to mention that, if you use += and just try to add to the textfield height instead of changing the textfield height, that the first line scrolls up the text box.
I tried:
if(test_txt.textHeight > test_txt.height) {
test_txt.height = (test_txt.height /(test_txt.numLines - 1)) * test_txt.numLines;
}
but text fields have some extras around the edges and stuff, so the text box got too big as time went by.
As a sidenote, I would like to mention that, if you use += and just try to add to the textfield height instead of changing the textfield height, that the first line scrolls up the text box.
Thursday, 27 May 2010
stageHeight after resize cont.
OK, it does pick it up, but technically, the stageHeight hasn't changed until the function has completed, so asking a movieClip to do something based on the new stageHeight when it hasn't actually changed yet is kind of silly...
stage.stageHeight after JavaScript's resize
I am trying to use the resize in an animation now, and I wanted the copyright movie clip to reposition itself when the movie got bigger. I got it to keep track of how far away it was from the bottom of the screen, but it didn't move, so I think perhaps that flash doesn't realise when it's stageHeight changes, but I will check on that now...
HTML Notation Converter
Right, two text boxes on stage, one input:
This code was also output using it, and I put the ampersand and quote marks in, because it was great at converting html into html notation, but my actual html notation was getting converted back to html by the blog editor!
It doesn't recognise all linebreaks, but it will pick up on the proper ones, web text is a bit funny like that...
htmlinput.text = '';
htmlinput.addEventListener(Event.CHANGE,outputhtml);
var htmlCode:Array = ['<','>',"\r",'&','"'];
var htmlNotation:Array = ['<','>',"\n",'&','"'];
function outputhtml(evnt:Event):void {
htmloutput.text = "<pre>";
var str:String = htmlinput.text;
for(var i:uint = 0; i<str.length; i++) {
var char:String = str.charAt(i);
trace(char+' '+str.charCodeAt(i));
var ind:int = htmlCode.indexOf(char);
if(ind == -1) {
htmloutput.appendText(char);
}else{
htmloutput.appendText(htmlNotation[ind]);
}
}
htmloutput.appendText("</pre>");
}
This code was also output using it, and I put the ampersand and quote marks in, because it was great at converting html into html notation, but my actual html notation was getting converted back to html by the blog editor!
It doesn't recognise all linebreaks, but it will pick up on the proper ones, web text is a bit funny like that...
Wednesday, 26 May 2010
Resize in IE
I don't know what the problem was, maybe it was something in the html code... I was using code I got from Flash 8 output.
Anyway...
This is the html (I had to alter the html to get past the blog editor), it works for both IE and FF:
It resizes the area for the swf, and it also outputs the width of the file on top of the swf - just so I can remember how to use the div tag later.
The actionscript is really quite simple:
btn.addEventListener(MouseEvent.CLICK,callIt);
function callIt(evnt:MouseEvent) {
bg.width += 20;
bg.height += 20;
ExternalInterface.call('resize',bg.width,bg.height);
}
And voila!
Anyway...
This is the html (I had to alter the html to get past the blog editor), it works for both IE and FF:
<body>
<script type="text/javascript">
function resize(wid,heig) {
var infoTag = document.getElementById("info");
var objectTag = document.getElementById("divtest");
var embedTag = document.getElementById("embedTag");
infoTag.innerHTML = wid;
objectTag.setAttribute("width",wid);
objectTag.setAttribute("height",heig);
embedTag.setAttribute("width",wid);
embedTag.setAttribute("height",heig);
}
</script>
<div id='info'></div>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="500" height="500" id="divtest" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="allowFullScreen" value="sameDomain" />
<param name="movie" value="divtest.swf" />
<param name="quality" value="high" />
<param name="scale" value="noscale" />
<param name="salign" value="lt" />
<param name="bgcolor" value="#ffffff" />
<embed id="embedTag" src="divtest.swf" loop="false" menu="false" quality="high" scale="noscale" bgcolor="#ffffff" width="500" height="500" name="divtest" align="middle" salign="lt" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />
</object>
</body>
It resizes the area for the swf, and it also outputs the width of the file on top of the swf - just so I can remember how to use the div tag later.
The actionscript is really quite simple:
btn.addEventListener(MouseEvent.CLICK,callIt);
function callIt(evnt:MouseEvent) {
bg.width += 20;
bg.height += 20;
ExternalInterface.call('resize',bg.width,bg.height);
}
And voila!
Subscribe to:
Posts (Atom)