2/6/2011 7:20:51 AM
Title:
Add image to sprite
Hi all
How can we add an image to a sprite in Flash Box2D in ActionScript?
I have the following code.But I don't know how to add an image into the sprite and set it to the userData of the bodyDef.
var sp:Sprite = new Sprite();
bodyDef.userData = sp;
Please give me a solution.
2/6/2011 7:37:50 AM
You can create a class to load an image inside a sprite like this :
// class to load image in sprite
package
{
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.*;
import flash.net.URLRequest;
import mx.controls.Alert;
public class SpriteBitmap extends Sprite
{
//path of image to be loaded
private var url:String = "myImage.jpg";
public function SpriteBitmap()
{
loadBitmap();
}
private function loadBitmap():void
{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, imageFailed);
var request:URLRequest = new URLRequest(url);
loader.load(request);
this.addChild(loader);
}
private function imageFailed(event:IOErrorEvent):void
{
Alert.show("Image loading failed");
}
}
}
code for MXML:
//call this function in your MXML to use above class
private function createSpriteBitmap():void
{
var mySprite:SpriteBitmap = new SpriteBitmap();
//add sprite to canvas container
myCanvas.rawChildren.addChild(mySprite);
}
2/6/2011 7:43:57 AM
hi check this link for loading images inside sprite in flash
http://www.flashwonderland.com/load-external-image/load-image-2.html
2/6/2011 7:50:21 AM
Thanks Efrain, it worked.
2/6/2011 9:46:16 AM
But the image is never aligning with the body?
Is there any method for aligning it with the body?
2/6/2011 10:30:28 AM
you can position the image using x, y properties
loader.x=100
loader.y =100
or you can create a new movieclip inside and sprite and loader to movieclip instead of adding it to root of sprite. Now you can position the movieclip using x and y properties .