Android Open Source - gameengine Box2 D World






From Project

Back to project page gameengine.

License

The source code is released under:

Apache License

If you think the Android project gameengine listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.garrapeta.gameengine;
/*from  w  ww . ja va2s  .  co m*/
import android.content.Context;
import android.graphics.PointF;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Joint;
import com.badlogic.gdx.physics.box2d.JointDef;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.World;
import com.garrapeta.gameengine.utils.LogX;

public abstract class Box2DWorld extends GameWorld implements ContactListener {

    // ----------------------------------------------- Constantes

    /** Nombre del thread del game loop */
    public static final String TAG = GameWorld.TAG + ".physics";

    /** Default phisical steps per second */
    private static final float DEFAULT_PHYSICAL_PERIOD = 60f; // (recomendado:
                                                              // 60Hertz)

    private static final int MAX_PHYSICAL_TIMESTEPS_PER_FRAME = 5;
    // ------------------------------------------------ Variables

    public World mBox2dWorld;
    private Vector2 mGravity;

    /** Target frequency of the of psyhical simulation, in seconds */
    private float mFrequency; //

    /** Target timestep of psyhical simulation, in seconds */
    private float mTimeStep;
    // ---------------------------------------------------- Inicializaci?n
    // est?tica

    static {
        LogX.i(TAG, "Attempting to load gdx native library");
        try {
            System.loadLibrary("gdx");
            LogX.i(TAG, "gdx native library loaded");
        } catch (Throwable t) {
            LogX.e(TAG, "Could not load gdx native library: " + t.toString());
            System.exit(1);
        }

    }

    // -------------------------------------------------------------
    // Constructores

    public Box2DWorld(GameView gameView, Context context, short soundLevel, short vibratorLevel) {
        super(gameView, context, soundLevel, vibratorLevel);
        mViewport.setReverseYAxis(true);
        // Step 1: Create Physics World Boundaries
        // worldAABB = new AABB();
        // worldAABB.lowerBound.set(new Vector2((float) 0, (float) 0));
        // worldAABB.upperBound.set(new Vector2((float) 100.0, (float) 100.0));

        // Step 2: Create Physics World with Gravity
        mGravity = new Vector2((float) 0.0, (float) 0.0);
        boolean doSleep = true;
        mBox2dWorld = new World(mGravity, doSleep);
        mBox2dWorld.setContactListener(this);
        mBox2dWorld.setAutoClearForces(false);

        setPhysicalFrequency(DEFAULT_PHYSICAL_PERIOD);
    }

    public void setPhysicalFrequency(float frequency) {
        mFrequency = frequency;
        mTimeStep = 1f / mFrequency;
    }

    // ------------------------------------------------------ mtodos de
    // GameWorld

    protected String getDebugString() {

        String actorCount;
        actorCount = String.valueOf(mActors.size());

        String bodyCount;
        bodyCount = String.valueOf(mBox2dWorld.getBodyCount());

        return actorCount + " actors " + bodyCount + " bodies " + super.getDebugString();
    }

    @Override
    void doProcessFrame(float lastFrameLength) {
        super.doProcessFrame(lastFrameLength);
        doPhysicalStep(lastFrameLength);
    }

    /**
     * Triggers physical simulation
     * 
     * @param time
     *            to emulate, in ms
     */
    private void doPhysicalStep(float time) {
        int steps = 0;
        time = time / 1000;

        float step = mTimeStep;
        if (time < step) {
            LogX.w(TAG, "Physical timestep higher than game timestep. Physical simulation can be unestable.");
            step = time;
        }
        while (time > 0 && steps < MAX_PHYSICAL_TIMESTEPS_PER_FRAME) {
            mBox2dWorld.step(step, 2, 1);
            time -= step;
            steps++;
        }
        mBox2dWorld.clearForces();
    }

    // mtodos relativos a unidades l?gicas / pantalla

    @Override
    protected void dispose() {
        super.dispose();
        mBox2dWorld.dispose();
    }

    // ---------------------------------------------------------- Mtodos
    // propios

    public Body createBody(Box2DActor<?> actor, PointF worldPos, boolean dynamic) {
        checkExecutedInGameLoopThread();

        BodyDef bodyDef = new BodyDef();

        bodyDef.position.set(worldPos.x, worldPos.y);

        Body body = mBox2dWorld.createBody(bodyDef);

        actor.addBody(body);
        body.setUserData(actor);

        if (dynamic) {
            body.setType(BodyType.DynamicBody);
        }

        return body;

    }

    public void destroyBody(Box2DActor<?> actor, Body body) {
        checkExecutedInGameLoopThread();
        body.setUserData(null);
        mBox2dWorld.destroyBody(body);
    }

    public void createJoint(Box2DActor<?> actor, JointDef jointDef) {
        Joint joint = mBox2dWorld.createJoint(jointDef);
        actor.addJoint(joint);
    }

    public void destroyJoint(Box2DActor<?> actor, Joint joint) {
        mBox2dWorld.destroyJoint(joint);
        actor.removeJoint(joint);
    }

    public float getGravityX() {
        return mBox2dWorld.getGravity().x;
    }

    public float getGravityY() {
        return mBox2dWorld.getGravity().y;
    }

    public void setGravityX(float gx) {
        mGravity.x = gx;
        mBox2dWorld.setGravity(mGravity);
    }

    public void setGravityY(float gy) {
        mGravity.y = gy;
        mBox2dWorld.setGravity(mGravity);
    }

    /**
     * Aplica una fuerza en un punto del mundo que afecta al actor
     * 
     * @param origin
     * @param target
     * @param radius
     * @param force
     */
    public void applyBlast(Vector2 origin, Body target, float radius, float force) {
        Vector2 aux = target.getWorldCenter()
                            .cpy();
        aux.sub(origin);

        float dist = aux.len();
        float diff = radius - dist;
        if (diff > 0) {
            float factor = diff / radius;
            aux.nor();
            aux.mul(force * factor);
            target.setAwake(true);
            target.applyLinearImpulse(aux, target.getWorldCenter());
        }
    }

    // ----------------------------------------------- mtodos de
    // ContactListener

    @SuppressWarnings("unchecked")
    @Override
    public void beginContact(Contact contact) {
        Body bodyA = contact.getFixtureA()
                            .getBody();
        Body bodyB = contact.getFixtureB()
                            .getBody();

        Box2DActor<Box2DWorld> actorA = (Box2DActor<Box2DWorld>) bodyA.getUserData();

        if (actorA != null) {
            Box2DActor<Box2DWorld> actorB = (Box2DActor<Box2DWorld>) bodyB.getUserData();
            if (actorB != null) {
                actorA.onBeginContact(bodyA, actorB, bodyB, contact);
                actorB.onBeginContact(bodyB, actorA, bodyA, contact);
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void endContact(Contact contact) {
        Body bodyA = contact.getFixtureA()
                            .getBody();
        Body bodyB = contact.getFixtureB()
                            .getBody();

        Box2DActor<Box2DWorld> actorA = (Box2DActor<Box2DWorld>) bodyA.getUserData();

        if (actorA != null) {
            Box2DActor<Box2DWorld> actorB = (Box2DActor<Box2DWorld>) bodyB.getUserData();
            if (actorB != null) {
                actorA.onEndContact(bodyA, actorB, bodyB, contact);
                actorB.onEndContact(bodyB, actorA, bodyA, contact);
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void preSolve(Contact contact, Manifold oldManifold) {
        Body bodyA = contact.getFixtureA()
                            .getBody();
        Body bodyB = contact.getFixtureB()
                            .getBody();

        Box2DActor<Box2DWorld> actorA = (Box2DActor<Box2DWorld>) bodyA.getUserData();
        if (actorA != null) {
            Box2DActor<Box2DWorld> actorB = (Box2DActor<Box2DWorld>) bodyB.getUserData();
            if (actorB != null) {
                actorA.onPreSolveContact(bodyA, actorB, bodyB, contact, oldManifold);
                actorB.onPreSolveContact(bodyB, actorA, bodyA, contact, oldManifold);
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void postSolve(Contact contact, ContactImpulse impulse) {
        Body bodyA = contact.getFixtureA()
                            .getBody();
        Body bodyB = contact.getFixtureB()
                            .getBody();

        Box2DActor<Box2DWorld> actorA = (Box2DActor<Box2DWorld>) bodyA.getUserData();
        if (actorA != null) {
            Box2DActor<Box2DWorld> actorB = (Box2DActor<Box2DWorld>) bodyB.getUserData();
            if (actorB != null) {
                actorA.onPostSolveContact(bodyA, actorB, bodyB, contact, impulse);
                actorB.onPostSolveContact(bodyB, actorA, bodyA, contact, impulse);
            }
        }
    }

}




Java Source Code List

com.badlogic.gdx.math.MathUtils.java
com.badlogic.gdx.math.Matrix3.java
com.badlogic.gdx.math.Matrix4.java
com.badlogic.gdx.math.Quaternion.java
com.badlogic.gdx.math.Vector2.java
com.badlogic.gdx.math.Vector3.java
com.badlogic.gdx.physics.box2d.BodyDef.java
com.badlogic.gdx.physics.box2d.Body.java
com.badlogic.gdx.physics.box2d.ChainShape.java
com.badlogic.gdx.physics.box2d.CircleShape.java
com.badlogic.gdx.physics.box2d.ContactFilter.java
com.badlogic.gdx.physics.box2d.ContactImpulse.java
com.badlogic.gdx.physics.box2d.ContactListener.java
com.badlogic.gdx.physics.box2d.Contact.java
com.badlogic.gdx.physics.box2d.DestructionListener.java
com.badlogic.gdx.physics.box2d.EdgeShape.java
com.badlogic.gdx.physics.box2d.Filter.java
com.badlogic.gdx.physics.box2d.FixtureDef.java
com.badlogic.gdx.physics.box2d.Fixture.java
com.badlogic.gdx.physics.box2d.JointDef.java
com.badlogic.gdx.physics.box2d.JointEdge.java
com.badlogic.gdx.physics.box2d.Joint.java
com.badlogic.gdx.physics.box2d.Manifold.java
com.badlogic.gdx.physics.box2d.MassData.java
com.badlogic.gdx.physics.box2d.PolygonShape.java
com.badlogic.gdx.physics.box2d.QueryCallback.java
com.badlogic.gdx.physics.box2d.RayCastCallback.java
com.badlogic.gdx.physics.box2d.Shape.java
com.badlogic.gdx.physics.box2d.Transform.java
com.badlogic.gdx.physics.box2d.WorldManifold.java
com.badlogic.gdx.physics.box2d.World.java
com.badlogic.gdx.physics.box2d.joints.DistanceJointDef.java
com.badlogic.gdx.physics.box2d.joints.DistanceJoint.java
com.badlogic.gdx.physics.box2d.joints.FrictionJointDef.java
com.badlogic.gdx.physics.box2d.joints.FrictionJoint.java
com.badlogic.gdx.physics.box2d.joints.GearJointDef.java
com.badlogic.gdx.physics.box2d.joints.GearJoint.java
com.badlogic.gdx.physics.box2d.joints.MouseJointDef.java
com.badlogic.gdx.physics.box2d.joints.MouseJoint.java
com.badlogic.gdx.physics.box2d.joints.PrismaticJointDef.java
com.badlogic.gdx.physics.box2d.joints.PrismaticJoint.java
com.badlogic.gdx.physics.box2d.joints.PulleyJointDef.java
com.badlogic.gdx.physics.box2d.joints.PulleyJoint.java
com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef.java
com.badlogic.gdx.physics.box2d.joints.RevoluteJoint.java
com.badlogic.gdx.physics.box2d.joints.RopeJointDef.java
com.badlogic.gdx.physics.box2d.joints.RopeJoint.java
com.badlogic.gdx.physics.box2d.joints.WeldJointDef.java
com.badlogic.gdx.physics.box2d.joints.WeldJoint.java
com.badlogic.gdx.physics.box2d.joints.WheelJointDef.java
com.badlogic.gdx.physics.box2d.joints.WheelJoint.java
com.badlogic.gdx.utils.Array.java
com.badlogic.gdx.utils.ComparableTimSort.java
com.badlogic.gdx.utils.Disposable.java
com.badlogic.gdx.utils.GdxRuntimeException.java
com.badlogic.gdx.utils.LongArray.java
com.badlogic.gdx.utils.LongMap.java
com.badlogic.gdx.utils.NumberUtils.java
com.badlogic.gdx.utils.Pool.java
com.badlogic.gdx.utils.Sort.java
com.badlogic.gdx.utils.StringBuilder.java
com.badlogic.gdx.utils.TimSort.java
com.garrapeta.MathUtils.java
com.garrapeta.gameengine.Actor.java
com.garrapeta.gameengine.AsyncGameMessage.java
com.garrapeta.gameengine.BitmapManager.java
com.garrapeta.gameengine.Box2DActor.java
com.garrapeta.gameengine.Box2DWorld.java
com.garrapeta.gameengine.GameMessage.java
com.garrapeta.gameengine.GameView.java
com.garrapeta.gameengine.GameWorld.java
com.garrapeta.gameengine.ShapeDrawer.java
com.garrapeta.gameengine.SyncGameMessage.java
com.garrapeta.gameengine.Viewport.java
com.garrapeta.gameengine.actor.Box2DAtomicActor.java
com.garrapeta.gameengine.actor.Box2DCircleActor.java
com.garrapeta.gameengine.actor.Box2DEdgeActor.java
com.garrapeta.gameengine.actor.Box2DLoopActor.java
com.garrapeta.gameengine.actor.Box2DOpenChainActor.java
com.garrapeta.gameengine.actor.Box2DPolygonActor.java
com.garrapeta.gameengine.actor.IAtomicActor.java
com.garrapeta.gameengine.actor.SimpleActor.java
com.garrapeta.gameengine.module.LevelActionsModule.java
com.garrapeta.gameengine.module.LoadedLevelActionsModule.java
com.garrapeta.gameengine.module.SoundModule.java
com.garrapeta.gameengine.module.VibrationModule.java
com.garrapeta.gameengine.utils.IOUtils.java
com.garrapeta.gameengine.utils.LogX.java
com.garrapeta.gameengine.utils.PhysicsUtils.java
com.garrapeta.gameengine.utils.Pool.java