Friday, May 28, 2010

Flash with PHP interaction

Flash with PHP interaction:
code in AS3.0

var userId:Number=10001;
var credit:Number=52;
var ticket:Number=10;
var varsToSend:URLVariables
function submitData(e:MouseEvent):void {
    varsToSend = new URLVariables();
    varsToSend.userId=userId;
    varsToSend.creadit=credit;
    varsToSend.ticket=ticket;

    // Create URL Request, set to POST, and attach data
    var formRequest:URLRequest=new URLRequest("score.php");
    formRequest.method=URLRequestMethod.POST;
    formRequest.data=varsToSend;

    // Create URL Loader, attach listeners, and load URL Request
    var varLoader:URLLoader=new URLLoader  ;
    varLoader.addEventListener(Event.COMPLETE, onLoaded);
    varLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
    varLoader.load(formRequest);
}

function onLoaded(e:Event):void {
    reciveData();
// success actions
}

function ioErrorHandler(e:IOErrorEvent):void {
    // I/O error actions
}
//
function reciveData():void {
    useridTxt.text=varsToSend.userId;
    creditTxt.text=varsToSend.credit;
    ticketTxt.text=varsToSend.ticket;
}
sendDataBtn.addEventListener(MouseEvent.CLICK, submitData);

code in PHP:

if(isset($_REQUEST['userId']))
{
    $userId = $_REQUEST['userId'];
    $creadit = $_REQUEST['creadit'];
    $ticket = $_REQUEST['ticket'];
}
 

Friday, April 9, 2010

Video object with the NetConnection and NetStream classes

This class creates a Video object in an Adobe Flash interface that plays either of the following kinds of video: recorded Flash Video (FLV) files stored on a server

or locally, or live video captured from a user's computer. A Video object is a display object on the application's display list and represents the visual space in which the video runs in a user interface.

You can control various properties of Video objects. For example, you can move the Video object around on the Stage by using its x and y properties, you can change its size using its height  and width properties, and so on. To play a video stream, use attachCamera() or attachNetStream()  to attach the video to the Video object. Then, add the Video object to the display list using addChild().


The following example uses a Video object with the NetConnection and NetStream classes to

load and play an FLV file. To run this example, you need an FLV file whose name and location

match the variable passed to videoURL, in this case, an FLV file called test.flv that is in

the same directory as the SWF file.

package {
    import flash.display.Sprite;
    import flash.display.*;
    import flash.events.*;
    import flash.media.Video;
    import flash.net.NetConnection;
    import flash.net.NetStream;

    public class VideoManagerextends Sprite {
        var ns:NetStream;
        var vid:Video;
        var vdoUrl:String = "test.flv";
        public function VideoManager() {
            var nc:NetConnection=new NetConnection  ;
            nc.connect(null);
            ns=new NetStream(nc);
            vid=new Video();
            vid.width=1024;
            vid.height=768;
            this.addChild(vid);
            vid.attachNetStream(ns);
            ns.play(vdoUrl);
            ns.addEventListener(NetStatusEvent.NET_STATUS,netstat);
            var netClient:Object=new Object  ;
            netClient.onMetaData=function(meta:Object){
            trace("duration:   "+meta.duration);
            };
            ns.client=netClient;
            // function for checking flv complete or not
            function netstat(stats:NetStatusEvent) {
                trace("info:  "+stats.info.code);
                if (stats.info.code=="NetStream.Buffer.Flush") {
                    ns.pause();
                    this.removeChild(vid);
                }
            }// end of the netstat function
        }// end of the function testComponentFlv
    }
}

1. Paste the class code into a new AS file and give the file the same name as the primary class  "VideoManager.as".
2. Create and save a new empty FLA file in the same directory as the AS file.
3. In the Properties tab of the Property inspector enter the class name of the primary class for the example in the Document class text box "VideoManager".
4. Save your changes to the FLA file.
5. Test the movie using the Control > Test Movie menu option.
6. Make sure test.flv is in the same directory as the SWF file.

Thursday, April 8, 2010

onEnterFrame

  • Description:

Event handler; invoked continually at the frame rate of the movie. The actions associated with the enterFrame clip event are processed before any frame actions that are attached to the affected frames.

You must define a function that executes when the event is invoked.This Event Handler Function is called at the start of each frame of display, whether the associated object is playing or not. However, if the sprite is removed, then the onEnterFrame actions are no longer processed. The Actions associated with the Event are processed before any Frame Action events for the object.

If "includingFirstFrame" is specified, then the actions will be processed on all frames of display starting from and including the very first frame that the object is placed. If "excludingFirstFrame" is specified, then it will not run for the first time until the frame AFTER the object is placed. Compare this with the onLoad Event Handler Function, which will run ONLY for the first frame of display.

The default if you specify neither option is "excludingFirstFrame" (this is the same behaviour as Flash uses for its enterFrame clip event).

This Event Handler is an ideal place to install collision detection routines for games, etc.

  • Syntax:

onEnterFrame = function() {}

  • Example of onEnterFrame:

1) The following example defines a function for the onEnterFrame event handler that sends a trace() action to the Output panel:

mc.onEnterFrame = function () {
    trace("come");
}


2) The following example defines a function for the onEnterFrame event handler that increase the size of a variable "i" by one and display it to a dynamic text "digit".


var i:Number = 0;
this.onEnterFrame = function() {
    i = i+1;
    digit.text = i;
};


  • onEnterFrame vrs setInterval:

onEnterFrame's time intervals are equal to the frame rate set in the document properties. If you want to run some code at different intervals of time, onEnterFrame won't be able to do the job. This is where setInterval is used. setInterval works like onEnterFrame except the time intervals are independent of the document's set frame rate. The timer measures the intervals in milliseconds, so you can run a function many times faster or slower that the document's frame rate.

Wednesday, April 7, 2010

volume slider in AS 3.0

A volume slider is a small bar that you can drag to increase or decrease the volume of any sound. In this tutorial, you will learn how to create just that.Let’s create a simple audio volume controller:

step 1) Copy and paste below code at first frame.
step 2) Make a movieClip for sound track named "track_mc".
step 3) Make another movieClie (for volume control) named "slider_mc" inside the "track_mc".
step 4) Insert sound (like .wav n .mp3) at first frame.



// AS 3.0 code for Volume Slider or Audio Control:

var soundVol:SoundTransform = new SoundTransform();
var soundVolume:Number = 1;

// Code that handles the volume slider
var trackBounds:Rectangle = track_mc.getBounds(track_mc);
var xPos:Number = trackBounds.x;
var yPos:Number = trackBounds.y;
var widthPos:Number = trackBounds.width-track_mc.slider_mc.width;
var heightPos:Number = 0;
var bounds:Rectangle = new Rectangle(xPos,yPos,widthPos,heightPos);
track_mc.slider_mc.x = widthPos;
track_mc.mouseEnabled = false;
track_mc.slider_mc.buttonMode = true;

track_mc.slider_mc.addEventListener(MouseEvent.MOUSE_DOWN,dragSlider);
stage.addEventListener(MouseEvent.MOUSE_UP,stopSlider);

function dragSlider(event:MouseEvent):void {
event.target.startDrag(false,bounds);
addEventListener(Event.ENTER_FRAME,setVolume);
}

function stopSlider(event:MouseEvent):void {
track_mc.slider_mc.stopDrag();
removeEventListener(Event.ENTER_FRAME, setVolume);
}
function setVolume(event:Event):void {
soundVolume = track_mc.slider_mc.x/widthPos;
soundVol.volume = soundVolume;
SoundMixer.soundTransform = soundVol;
}

Wednesday, March 31, 2010

Server-side interaction in Flash:

In this tutorial i just want to describe you how to send data from Flash to a server side language. In this tutorial shows the basics of this common practice using PHP as the server side language.


stop();
var _score:Number;
var _levelNo:int;
var myVars: LoadVars = new LoadVars();
myVars.load("http://*.*.*.*/Flash/serverScriptExample/test.php");
myVars.onLoad = function(success) {
if (success) {
_score = myVars.score;
_levelNo = myVars.level;
} else {
trace("File Failed to open!");
}
};

The latest Flash MX has introduced a new Object type called LoadVars() that simplify the exchange of data between client and server.
On the PHP side, things are simple, since the way to return data to Flash is a query basically to return the two variables to the Flash movie you can output something like "score=120&lives=2".

This can be done in PHP with something like this:



$score = 120;
$level = 2;
echo "score=$score&level =$level ";


The techniques shown in this article can be used also to interact with other application servers, based on other languages such as ASP .NET, JSP etc
There's another useful method in the LoadVar object called SendAndLoad() which let you exchange data with the server in a bi-directional way. Here's an example :


// myVars is LoadVars object
var myVars:LoadVars = new LoadVars();
// these are the vars the are going to be sent
myVars.score = _score;
myVars.levelNo = _levelNo;
// handling the load event
loadObj.onLoad = function(success) {
if ((success)) {
trace("loading successfully");
} else {
trace("loading problem");
}
};
// Send and Load data
myVars.sendAndload(("http://*.*.*.*/Flash/serverScriptExample/test.php","myVars","post");



This can be done in PHP with something like this:


$score = $_POST[ ' _score ' ];
$levelNo = $_POST[ ' _levelNo' ];


Basically, you can send variables from flash to any serverside programming language. At the serverside (such as PHP), you get the data using the $_POST["var1"] or $_GET["var2"] depends on you send variables as POST or GET. When you want to send data from PHP back to flash, try to read this method: LoadVars().

Wednesday, March 3, 2010

Save image with flash and php


Here is the code to save the image through flash action script 2.0. Use the BitmapData class in action script 2.0 and get the data in string format that is basically value of each pixel and send the data 2 PHP file on the server. PHP file would prepare the header of the required image format and save the JPEG, PNG on the server as well and then at last when JPEG, PNG is saved than prompt user to download JPEG, PNG on their PC. :)
Action script 2.0
stop();
import flash.display.*;
 function sendImg () {
                var bmpData:BitmapData= new BitmapData(fighter_mc._width, fighter_mc._height);
                bmpData.draw(fighter_mc);
                var _pixels:Array = new Array();
                var _w:Number = bmpData.width;
                var _h:Number = bmpData.height;
                for (var i = 0; i<=_w; i++) {
                                for (var j = 0; j<=_h; j++) {
                                                var tmp = bmpData.getPixel(i,j ).toString(16);
                                                _pixels.push(tmp);
                                }
                }
                var lv:LoadVars = new LoadVars();
                lv.img = _pixels.toString();
                lv.height = _h;
                lv.width = _w;
                lv. sendAndLoad ("show.php", " lv ", "POST");
}
doneBtn.onPress = function() {
                sendImg();
};


PHP:
                $data = explode(",", $_POST['img']);
                $width = $_POST['width'];
                $height = $_POST['height'];
               
                $image=imagecreatetruecolor( $width ,$height );
                $background = imagecolorallocate( $image ,0 , 0 , 0 );
                //Copy pixels
                $i = 0;
                for($x=0; $x<=$width; $x++){
                                for($y=0; $y<=$height; $y++){
                                                $int = hexdec($data[$i++]);
                                                $color = imageColorAllocate ($image, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
                                                imagesetpixel ( $image , $x , $y , $color );
                                }
                }
                //Output image and clean
                header( "Content-type: image/jpeg" );
                ImageJPEG( $image );
                imagedestroy( $image );              
?>

Friday, February 26, 2010

HEX to RGB

Color can sometimes make or break your design.
It’s even nice for translating a Hexadecimal color into RGB color.


var color = 0x00cc00
var rgbObject = hex2rgb(color);
function hex2rgb (hex):Object{
var red = hex>>16;
var greenBlue = hex-(red<<16) var green = greenBlue>>8;
var blue = greenBlue - (green << 8);
return({r:red, g:green, b:blue});
}

Thursday, January 21, 2010

Play sound as a LOOP in AS3

//In AS3 an event Event.SOUND_COMPLETE that fires when the sound finishes, so when that fires you should start the sound again, and your sound will be play as a loop.


var sndReq:URLRequest=new URLRequest("Assets/Audio/drums01.mp3");
var snd:Sound = new Sound();
var channel:SoundChannel = new SoundChannel();
snd.load(sndReq);
soundOn.addEventListener(MouseEvent.CLICK, playSound);
soundOff.addEventListener(MouseEvent.CLICK, stopSound);
function playSound(event:MouseEvent):void {
channel=snd.play();
channel.addEventListener(Event.SOUND_COMPLETE,loopSound);
}
function loopSound(event:Event) {
playSound();
}
function stopSound(event:MouseEvent):void {
channel.stop();
}

Monday, January 18, 2010

Loading External Sound

Sound, whether in the form of music or sound effects, is an important part of any flash game. While you may be able to get away with controlling sound with the time-line in an animation, a game must be a bit more dynamic and you will almost always need to control the sound with action-script. This tutorial will help you understand not only control sound in action-script 2, but avoid potential problems.
Loading external sound into your Flash projects using AS2 is a fairly easy task. Using AS3 to load external sounds is just as simple. I am going to quickly go over how to load an external sound file using AS3 in comparison to AS2 syntax.

Loading external sound using AS2

var snd:Sound = new Sound ();
snd.loadSound("song.mp3", true);
snd.onSoundComplete = function() {
snd.start();
};


Loading external sound using AS3



var snd:Sound = new Sound();
var channel:SoundChannel = new SoundChannel();
snd.load(new URLRequest("song.mp3"));
snd.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
function onComplete(evt:Event):void {
channel = snd.play();
}

In AS3 the SoundChannel class is used to create a separate channel for each new sound played. By placing each sound in its own channel, you can work with multiple sounds but control each sound separately.