Search code examples
actionscript-3flashbox2dflashdevelop

Adding sprite to box2d object in flash AS3


I'm pretty new to flash and box2d. I've managed to get around the basics of box2d no bother, but up till now, I've been using the b2debugdraw function to display all the objects I've been created. So I decided I should start looking into how to actually add sprites or images to my objects.

I've hopelessly searched on google for hours now and I'm completely frustrated at this point so I'd really appreciate if one of you guys could give me a hand figuring this out, all I'm trying to do is add the image/sprite of a crate I made to a square I made with box2d.

Here is my most recent attempt:

package 
{
import Box2D.Collision.b2AABB;
import Box2D.Collision.Shapes.b2PolygonShape;
import Box2D.Common.Math.b2Vec2;
import Box2D.Dynamics.b2Body;
import Box2D.Dynamics.b2BodyDef;
import Box2D.Dynamics.b2DebugDraw;
import Box2D.Dynamics.b2Fixture;
import Box2D.Dynamics.b2FixtureDef;
import Box2D.Dynamics.b2World;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;


/**
 * ...
 * @author Robert Damery
 */
public class Main extends Sprite 
{
    //World object
    public var world:b2World;
    //Scale number
    public const scale:int = 30;
    //Time Counter
    public var Counter:int = 60;

    public var boxbody:Sprite;

    public function Main():void 
    {
        var asprite:Sprite;
        asprite.graphics.beginBitmapFill(crate.jpg, null, false, false);
        asprite.graphics.drawRect(0, 0, 25, 25);
        asprite.graphics.endFill();
        asprite.x = 100;
        asprite.y = 100;
        stage.addChild(asprite);

        // create world
        CreateWorld();
        //Create a box function
        CreateBox(300, 600, 600, 25, false, .8);
        CreateBox(0, 600, 25, 600, false, .8);
        CreateBox(800, 0, 25, 600, false, .8);
        CreateBox(400, 100, 25, 25, true, .8);

        //Make frames pass in flash
        addEventListener(Event.ENTER_FRAME, newframeevent);
        //Draw our debug data
        debug_draw();
    }

    //Event handler function, makes time go by
    private function newframeevent(e:Event):void 
    {
        world.Step(1 / 30, 10, 10);
        world.ClearForces();
        world.DrawDebugData();
    }

    private function CreateWorld():void 
    {
        //Size of World
        var worldsize:b2AABB = new b2AABB();
        worldsize.lowerBound.Set(-500, -500);
        worldsize.upperBound.Set(500 , 500);
        //Define Gravity
        var gravity:b2Vec2 = new b2Vec2(0 , 9.8);
        // Ignore sleeping objects
        var doSleep:Boolean = true;
        world = new b2World(gravity, doSleep);
    }

    private function CreateBox(x:Number, y:Number, width:Number, height:Number, is_Dynamic:Boolean, density:Number):b2Body
    {
        x = con2D(x);
        y = con2D(y);
        width = con2D(width);
        height = con2D(height);

        //Create the body definition
        var floorshapedef:b2BodyDef = new b2BodyDef();
        floorshapedef.position.Set(x, y);
        //Determine whether object is dynamic or not
        if (is_Dynamic == true)
        {
            floorshapedef.type = b2Body.b2_dynamicBody;
        }
        else
        {
        floorshapedef.type = b2Body.b2_staticBody;
        }
        //Create the shape
        var floorshape:b2PolygonShape = new b2PolygonShape();
        floorshape.SetAsBox(width, height);

        //Create the fixture
        var floorfixture = new b2FixtureDef();
        floorfixture.shape = floorshape;
        floorfixture.density = density;
        floorfixture.restitution = .5;
        floorfixture.friction = .25;

        //Create body
        var floorbody:b2Body = world.CreateBody(floorshapedef);
        floorbody.CreateFixture(floorfixture);

        return floorbody;

    }

        //Debug Draw function
        public function debug_draw():void
    {
        var debug_draw:b2DebugDraw =  new b2DebugDraw();
        var debug_sprite:Sprite = new Sprite();
        addChild(debug_sprite);
        debug_draw.SetSprite(debug_sprite);
        debug_draw.SetDrawScale(scale);
        debug_draw.SetFlags(b2DebugDraw.e_shapeBit);
        world.SetDebugDraw(debug_draw);

    }

    public function con2D(num:Number):Number
    {
        return num / scale;
    }


}

}

I already know that I haven't even attempted attaching the sprite to the box, but that is because I haven't been able to even make the box show up. When I run this particular code I get an error saying: Access of undefined property crate.

I have the same image in various formats, including .fla, but I get the same error all the time.


Solution

  • Here, this is a long list of tutorials for box2d. As for adding sprite to Box2d, you are thinking the wrong way. Box2d is a physic engine that simulates real time physics. Using DebugDraw will provide basic graphics for your shapes.

    Rendering and Physic simulation are two seperate "threads" that runs along each other.

    What you need to do is have your Graphics emulate where the shapes are. So on your OnEnterFrame event you should have your sprites take the positions, rotations, scales from your box2d shapes. Also dont forget that box2d is in metric system and flash is in pixels, use a conversion constants. Everything is explain in the link below, take the time to read it.

    http://www.kerp.net/box2d/

    Hope this helps : )