var best_arr:Array=new Array(new Array(1,'abc'),new Array(9,'abc'),new Array(1,'abc'),new Array(10,'abc'));
//best_arr.sortOn(Array,Array.NUMERIC );
best_arr=newSort(best_arr,0)
trace(best_arr);
function newSort(arr:Array,soryBy:int):Array{
var temp_arr:Array=new Array();
var sort_arr:Array=new Array();
var i:int;
for(i=0;i<arr.length;i++){
sort_arr.push({number:arr[i][soryBy],oldsort:i});
}
sort_arr.sortOn('number',Array.NUMERIC |Array.DESCENDING );
for(i=0;i<sort_arr.length;i++){
temp_arr[i]=arr[sort_arr[i].oldsort];
}
return temp_arr
}
as3 Two-dimensional array sort
as3 facebook application new login permission
use GraphAPI 1.8.1
Facebook.login(handleLogin,{perms:"email"});
replace to
Facebook.login(handleLogin,{scope:"email"});
as3 facebook application double scroll bar
http://www.hyperarts.com/blog/facebook-iframe-apps-getting-rid-of-scrollbars/
as3 search string or array
var a:String="gamaniasen";
var b:String='sen';
var i:int
var Len:int=a.length;
var space:int=b.length;
for(i=0;i
trace("true")
}
}
as3 A depth higher then B
this.setChildIndex(A,this.getChildIndex(B));
as3 array random sort
var temp_array:Array = new Array(1,2,3,4,5)
temp_array.sort(randomSort)
trace(temp_array )
function randomSort(a:Object, b:Object):Number{
var r:Number = Math.random() - Math.random();
if(r >0)return 1;
if(r< 0)return -1;
return 0;
}
as3 load XML
XML
<?xml version="1.0"?>
<config>
<api><![CDATA[http://xxx]]></api>
<secure><![CDATA[1]]></secure>
</config>
AS
function loadXML():void{
var request_show:URLRequest = new URLRequest("frame/config.xml");
var loader_php:URLLoader = new URLLoader(request_show);
loader_php.addEventListener(Event.COMPLETE,search_Complete);
loader_php.load(request_show);
}
function search_Complete(e:Event):void {
configXML = XML(e.target.data);
trace(configXML.api[0].text());//output: http://xxx
trace(configXML.secure[0].text());//output: 1
}
as3 unixtime
var myDate = new Date();
trace(myDate);
var unixTime = Math.round(myDate.getTime()/1000);
trace("Unix Time: "+unixTime);
var dateNew = new Date();
dateNew.setTime(unixTime);
trace(dateNew);
as3 TLFTextfield's text Always update, memory can't be release
TLFTextfield的文字如果不斷更新~~記憶體不會被釋放
if TLFTextfield's text Always update, memory can't be release
as3 textfield alpha
txt.blendMode = BlendMode.LAYER;
AS3 distance between two points
way 1
function DistanceTwoPoints(x1:Number, x2:Number, y1:Number, y2:Number):
Number {
var dx:Number = x1-x2;
var dy:Number = y1-y2;
return Math.sqrt(dx * dx + dy * dy);
}
way 2
var pt1:Point = new Point(circle1.x, circle1.y);
var pt2:Point = new Point(circle2.x, circle2.y);
var distance:Number = Point.distance(pt1, pt2);
as3 eventListener function with parameter
mc.addEventListener(Event.COMPLETE,function(e : Event) : void{LoadedComplete(e, 'test' ,true);});
function LoadedComplete(e:Event,txt:String,switch:Boolean ):void{
}
clear DNS cache
for win
in command line:
ipconfig /flushdns
for mac
in terminal
dscacheutil -flushcache
as3 embed youtube player fullscreen problem
stage.addEventListener(FullScreenEvent.FULL_SCREEN, fullScreenHandler);
function fullScreenHandler(e:FullScreenEvent) {
if(!e.fullScreen){ //you just returned back to normal
topMC.addChild(player);
player.setSize(640, 360)
}else{ //you just entered full screen mode
xxx.addChild(player);
player.setSize(stage.stageWidth, stage.stageHeight)
}
};
mc change depth to top
this.setChildIndex(mc, this.numChildren-1)
as3 sound fade in fade out
// Initialize sound variables
var so:Sound = new Sound();
var sc:SoundChannel;
var fadeInIncr = 0.1;
var sAmbienceVol:SoundTransform = new SoundTransform(fadeInIncr, 0); // 1=vol, 0=pan
var soundFadeOutTimer:Timer = new Timer(100,10);
var soundFadeInTimer:Timer = new Timer(100,10);
soundFadeOutTimer.addEventListener("timer", soundFadeOut);
soundFadeInTimer.addEventListener("timer", soundFadeIn);
soundFadeOutTimer.addEventListener(TimerEvent.TIMER_COMPLETE, soundOutComplete);
soundFadeInTimer.addEventListener(TimerEvent.TIMER_COMPLETE, soundInComplete);
loadMusic()
var soundFadeInSwitch:Boolean =false;
var soundFadeOutSwitch:Boolean =true;
function loadMusic():void{
so = new Sound(new URLRequest("xxx.mp3"));
so.addEventListener(Event.COMPLETE, soundLoadComplete);
so.addEventListener(ProgressEvent.PROGRESS, soundprogressHandler);
}
function soundprogressHandler(event:ProgressEvent):void {
var loadTime:Number = event.bytesLoaded / event.bytesTotal;
var loadPercent:uint = Math.round(100 * loadTime);
sound_mc.loaded_txt.text =loadPercent + "%";
}
function soundLoadComplete(event:Event):void {
sound_mc.loaded_txt.text ="";
startMusic();
sc = so.play(0, 1, sAmbienceVol);
}
function stopMusic():void{
soundFadeOutSwitch=false;
soundFadeOutTimer.reset();
soundFadeOutTimer.start()
}
function startMusic():void{
soundFadeInSwitch=false;
soundFadeInTimer.reset();
soundFadeInTimer.start()
}
function soundFadeOut(e:TimerEvent){
trace(fadeInIncr);
if(fadeInIncr>0){
fadeInIncr -= 1/10;
}else{
fadeInIncr=0;
soundFadeOutTimer.stop();
}
sAmbienceVol = new SoundTransform(fadeInIncr, 0);
sc.soundTransform = sAmbienceVol;
}
function soundFadeIn(e:TimerEvent){
trace(fadeInIncr);
if(fadeInIncr<=1){
fadeInIncr += 1/10;
}else{
fadeInIncr=1;
soundFadeInTimer.stop();
}
sAmbienceVol = new SoundTransform(fadeInIncr, 0);
sc.soundTransform = sAmbienceVol;
}
function soundInComplete(e:TimerEvent):void {
sAmbienceVol = new SoundTransform(1, 0);
sc.soundTransform = sAmbienceVol;
soundFadeInSwitch=true;
}
function soundOutComplete(e:TimerEvent):void {
sAmbienceVol = new SoundTransform(0, 0);
sc.soundTransform = sAmbienceVol;
soundFadeOutSwitch=true;
}
Firefox/Chrome Flash TextField can't type chinese
html wmode -> Window ->done!
as3 sound length and position
var so:Sound = new Sound();
var sc:SoundChannel;
so = new Sound(new URLRequest("xxx.mp3"));
so.addEventListener(Event.COMPLETE, soundLoadComplete);
sc = so.play();
function soundLoadComplete(event:Event):void {
}
sc.position //song right now position
so.length //song total length
AS3 Delete all child from MC
while (mc.numChildren) {
mc.removeChildAt(0);
}
as3 call javascript function
import flash.external.ExternalInterface;
ExternalInterface.call("your_javascript_function","params1","params2","etc");
javascript show or hide div
<script language="javascript">
function toggle() {
var ele = document.getElementById("toggleText");
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
</script>
<div id="toggleText" style="display: none">
<h1>test</h1>
</div>
call as3 function from javascript use swfobject
JS code
var flashObj = document.getElementById("flash_id");// must have real ID you passed to SWFObject
flashObj.getFromJavaScript();
AS3 code
import flash.external.ExternalInterface;
ExternalInterface.addCallback("getFromJavaScript", anActionScriptMethod);
function anActionScriptMethod():void{
//do something
}
get page info from facebook graph api
import com.adobe.serialization.json.JSON;
Security.loadPolicyFile("http://graph.facebook.com/crossdomain.xml");
var myLoader:URLLoader = new URLLoader();
myLoader.load(new URLRequest("http://graph.facebook.com/http://www.google.com/"));
myLoader.addEventListener(Event.COMPLETE, Complete);
}
function Complete(e:Event):void{
trace(JSON.decode(e.target.data));
}
use json get it
5005: unknown error optimizing byte code
computer -> properties -> advanced -> environment vars -> then make a new var like this
JAVA_TOOL_OPTIONS
and its value
-Xmx1024M
我的電腦 > 右鍵內容 > 進階 > 環境變數 > 系統變數"新增"變數值 > 名稱 JAVA_TOOL_OPTIONS > 值 -Xmx1024M
(1024 or 512..256..128)
Tween function
Linear.easeNone
Back
Bounce
Circ
Cubic
Elastic
Expo
Quart
Quint
Sine
(xxx.easeIn, xxx.easeOut, xxx.easeInOut)
AS3 fullscreen or not
stage.displayState=StageDisplayState.FULL_SCREEN;
stage.displayState=StageDisplayState.NORMAL;
http can't find index.html??
ftp root folder -> .htaccess
DirectoryIndex index.htm index.html index.php
google tracking
in html
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxxxxx-x']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
function GAPageView(url){_gaq.push(['_trackPageview', url]);}
function GAEventTrack(category, action, label){_gaq.push(['_trackEvent', category, action, label]);}
</script>
in as
tracking page view
GATracking.trackPageview("/index");
tracking event
GATracking.trackEvent("/index", "action", "做了啥");
GATracking.as -> author jacky
compare round, floor, ceil
int();無條件捨去
Math.round();四捨五入
Math.floor();無條件捨去
Math.ceil();無條件進位
SWF get parameter from html
in js
<script type="text/javascript">
function $G(){
var Url=top.window.location.href;
var u,g,StrBack='';
if(arguments[arguments.length-1]=="#")
u=Url.split("#");
else
u=Url.split("?");
if (u.length==1) g='';
else g=u[1];
if(g!=''){
gg=g.split("&");
var MaxI=gg.length;
str = arguments[0]+"=";
for(i=0;i<MaxI;i++){
if(gg[i].indexOf(str)==0) {
StrBack=gg[i].replace(str,"");
break;
}
}
}
return StrBack;
}
</script>
embedSWF("index.swf?id="+$G("param") , "flashcontent" , "100%" , "100%" , "10.0.0.0");
in html
index.swf?param=xxx
in as3
loaderInfo.parameters.param;
can get xxx
bitmap to png or jpg
import com.adobe.images.PNGEncoder;
import com.adobe.images.JPGEncoder;
var _bitmapData:BitmapData = new BitmapData(mc.width,mc.height);
_bitmapData.draw(mc);
var _byte:ByteArray = PNGEncoder.encode(_bitmapData);
//var _byte:ByteArray = JPGEncoder.encode(_bitmapData);
var _file:FileReference = new FileReference();
_file.save(_byte ,"file.png");
Facebook Graph api fql.query cookie fix
Facebook.fqlQuery("SELECT type, page_id FROM page_fan WHERE uid= "+uid+
" and page_id="+pageID+" and "+randRange(0,100), callbackfunction);
send random int!!!
Check Email Format
function isValidEmailAddress($str:String):Boolean {
return (($str == findValidEmailAddress($str)) ? true : false);
}
function findValidEmailAddress($str:String):String {
var pattern:RegExp = /\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/gi;
var result:Object = pattern.exec($str);
return ((result == null) ? "" : result[0]);
}
AS3 Performance note
Object pool > new Sprite();
array[0]='string' > array.push('string');
switch case > if else
* > /
for(i=0;i<j;i++) > for(var i=0;i<array.length;i++)
p.s remove listener(enterframe, mousemove, timer) when object remove on stage
AS3 setTimeout and Timer
setTimeout(function(){
}, 5000);
var myTimer:Timer= new Timer(5000, 1);
myTimer.addEventListener("timer", timerHandler);
myTimer.start();
function timerHandler(event:TimerEvent):void {
trace("timerHandler: " + event);
}
AS3 Random Range
function randRange(minNum:Number, maxNum:Number):Number {
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
AS3 on resize
stage.addEventListener(Event.RESIZE, resizeHandler);
function resizeHandler(e:Event):void{
reSize();
}
function reSize():void{
}
reSize();
AS3 Open URL
navigateToURL(new URLRequest("http://www.google.com.tw"), '_blank');
'_self' also
in Chinese case
navigateToURL(new URLRequest(encodeURI("http://www.google.com.tw?中文")), '_blank');
js
var js:URLRequest=new URLRequest();
js.url="javascript:window.open('award.html','popper1','width=540,height=360');newWindow.focus(); void(0);";
pop_btn.addEventListener(MouseEvent.CLICK,openPopUp);
function openPopUp(evt:MouseEvent):void{
navigateToURL(js,'_self');
}
Facebook Graph API Login, PostData
facebook init
Facebook.init('App ID', initLogin);
function initLogin(response:Object, fail:Object):void {//facebook init
}
facebook login
Facebook.login(handleLogin,{perms:"user_birthday,read_stream,publish_stream,user_photos"});
function handleLogin(response:Object, fail:Object):void {//facebook login
if(response!=null){
Facebook.api('/me', onMyInfoLoaded);
}
}
load facebook info and post data
function onMyInfoLoaded(response:Object,fail:Object):void {//facebook info success
if(response!=null){
var params:Object = {
source: 'http://xxx.jpg',
picture: 'http://xxx.jpg',
message: 'text',
link: 'http://adidas-oba2011-2.youthwant.com.tw',
name: 'Adidas is all in',
caption: '內容',
description: '內容'
};
Facebook.postData('/me/feed', requestHandler, params);
}
}
function requestHandler(result:Object, fail:Object):void{
if (result != null){
if (result.error_msg != null){
//error
}else{
//success
}
}
if (fail != null){
//error
}
}
Adobe Flash Player Debug
always for facebook application debug
Debug Flash Player
http://www.adobe.com/support/flashplayer/downloads.html
Get Params From SWF
loaderInfo.parameters.id
in as can get http://yoururl.com/xxx.swf?id=xxx
Crossdomain Load Image as Bitmap
var loaderContext:LoaderContext = new LoaderContext ();
loaderContext.checkPolicyFile = true;
loaderContext.applicationDomain = ApplicationDomain.currentDomain;
pic_loader.load(new URLRequest("url"), loaderContext);
Social Website URL Share
twitter:
http://twitter.com/?status=xxx http://xxx
plurk:
link: http://plurk.com/?status=www.google.com(xxx)
image: http://plurk.com/?status=http://xxx.jpg
facebook:
http://www.facebook.com/share.php?u=http://xxx