Physics Game in jme3 - Java Game

Java examples for Game:JME3

Description

Physics Game in jme3

Demo Code

package Physics;//ww w  .j av a 2s  .c  o m

import com.jme3.app.SimpleApplication;
import com.jme3.asset.plugins.HttpZipLocator;
import com.jme3.asset.plugins.ZipLocator;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.control.BetterCharacterControl;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.light.AmbientLight;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.scene.CameraNode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.control.CameraControl;
import com.jme3.scene.shape.Box;
import com.jme3.scene.shape.Sphere;

/**
 * test
 *
 * @author normenhansen
 */
public class PhysicsGame extends SimpleApplication implements
        ActionListener {

    private BulletAppState bulletAppState;
    private Node sceneNode;
    private Node crateNode;
    private Node playerNode;
    private CameraNode camNode;
    private Material crateMat;
    private Material sceneMat;
    private static Box crateMesh;
    private RigidBodyControl cratePhy;
    private RigidBodyControl scenePhy;
    private RigidBodyControl ballPhy;
    private int speed = 80;
    private BetterCharacterControl playerControl;
    private boolean rotateLeft = false, rotateRight = false,
            forward = false, backward = false, strafeLeft = false,
            strafeRight = false;
    private Vector3f walkDirection = new Vector3f(0, 0, 0);
    private Vector3f viewDirection = new Vector3f(0, 0, 1);
    private static final float BRICK_LENGTH = 0.4f;
    private static final float BRICK_WIDTH = 0.3f;
    private static final float BRICK_HEIGHT = 0.25f;

    static {
        crateMesh = new Box(BRICK_LENGTH, BRICK_HEIGHT, BRICK_WIDTH);
        //        ballMesh = new Sphere(32, 32, 0.25f, true, false);
        //        ballMesh.setTextureMode(Sphere.TextureMode.Projected);

    }

    public static void main(String[] args) {
        PhysicsGame app = new PhysicsGame();
        app.start();
    }

    @Override
    public void simpleInitApp() {
        initPhysics();
        initLight();
        initMaterials();
        initScene();
        initCharacter();
        initCamera();
        initNavigation();
    }

    /**
     * Initialize the physics simulation
     */
    private void initPhysics() {
        bulletAppState = new BulletAppState();
        stateManager.attach(bulletAppState);
        bulletAppState.setDebugEnabled(true); // collision shapes visible
    }

    private void initScene() {
        // 1. Load the scene node
        assetManager.registerLocator("quake3level.zip", ZipLocator.class);
        sceneNode = (Node) assetManager.loadModel("main.meshxml");
        sceneNode.scale(1f);
        rootNode.attachChild(sceneNode);
        // 2. Create a RigidBody PhysicsControl with mass zero
        // 3. Add the scene's PhysicsControl to the scene's geometry
        // 4. Add the scene's PhysicsControl to the PhysicsSpace
        scenePhy = new RigidBodyControl(0f);
        sceneNode.addControl(scenePhy);
        bulletAppState.getPhysicsSpace().add(scenePhy);
    }

    /* Set up collision detection for 1st-person player. 
     * The player control itself has no visible geometry or location:
     * for a 3rd-person player, attach a geometry to the playerNode. */
    private void initCharacter() {
        // 1. Create a player node.
        playerNode = new Node("the player");
        playerNode.setLocalTranslation(new Vector3f(200, 40, 200));
        rootNode.attachChild(playerNode);
        // 2. Create a Character Physics Control.
        playerControl = new BetterCharacterControl(.5f, 4, 30f);
        // 3. Set some properties of Character Physics Control
        playerControl.setJumpForce(new Vector3f(0, 300, 0));
        playerControl.setGravity(new Vector3f(0, -10, 0));
        // 4. Add the player control to the PhysicsSpace
        playerNode.addControl(playerControl);
        bulletAppState.getPhysicsSpace().add(playerControl);
    }

    /**
     * CameraNode depends on playerNode. The camera follows the player.
     */
    private void initCamera() {
        camNode = new CameraNode("CamNode", cam);
        camNode.setControlDir(CameraControl.ControlDirection.SpatialToCamera);
        camNode.setLocalTranslation(new Vector3f(0, 100, -6));
        Quaternion quat = new Quaternion();
        quat.lookAt(Vector3f.UNIT_Z, Vector3f.UNIT_Y);
        camNode.setLocalRotation(quat);
        playerNode.attachChild(camNode);
        camNode.setEnabled(true);
        flyCam.setEnabled(false);
    }

    public Geometry makeCrate(Vector3f loc) {
        Geometry crateGeo = new Geometry("crate", crateMesh);
        crateGeo.setMaterial(crateMat);
        crateNode.attachChild(crateGeo);
        crateGeo.move(loc);
        cratePhy = new RigidBodyControl(10f);
        crateGeo.addControl(cratePhy);
        cratePhy.setFriction(0.1f);
        bulletAppState.getPhysicsSpace().add(cratePhy);
        return crateGeo;
    }

    private void initLight() {
        DirectionalLight sun = new DirectionalLight();
        sun.setDirection(new Vector3f(1.1f, -1.3f, -2.1f));
        rootNode.addLight(sun);
        AmbientLight al = new AmbientLight();
        al.setColor(ColorRGBA.White.mult(1.5f));
        rootNode.addLight(al);
    }

    private void initMaterials() {
        crateMat = assetManager.loadMaterial("Materials/bark.j3m");
    }

    private void initNavigation() {
        flyCam.setMoveSpeed(100);
        inputManager.addMapping("Forward", new KeyTrigger(KeyInput.KEY_W));
        inputManager.addMapping("Back", new KeyTrigger(KeyInput.KEY_S));
        inputManager.addMapping("Rotate Left", new KeyTrigger(
                KeyInput.KEY_A));
        inputManager.addMapping("Rotate Right", new KeyTrigger(
                KeyInput.KEY_D));
        inputManager.addMapping("Jump", new KeyTrigger(KeyInput.KEY_SPACE));
        inputManager.addMapping("Strafe Left", new KeyTrigger(
                KeyInput.KEY_Q));
        inputManager.addMapping("Strafe Right", new KeyTrigger(
                KeyInput.KEY_E));
        inputManager.addListener(this, "Forward", "Rotate Left",
                "Rotate Right");
        inputManager.addListener(this, "Back", "Strafe Right",
                "Strafe Left", "Jump");
    }

    public void onAction(String binding, boolean isPressed, float tpf) {
        if (binding.equals("Rotate Left")) {
            rotateLeft = isPressed;
        } else if (binding.equals("Rotate Right")) {
            rotateRight = isPressed;
        } else if (binding.equals("Strafe Left")) {
            strafeLeft = isPressed;
        } else if (binding.equals("Strafe Right")) {
            strafeRight = isPressed;
        } else if (binding.equals("Forward")) {
            forward = isPressed;
        } else if (binding.equals("Back")) {
            backward = isPressed;
        } else if (binding.equals("Jump")) {
            playerControl.jump();
        }
    }

    @Override
    public void simpleUpdate(float tpf) {

        // Get current forward and left vectors of the playerNode: 
        Vector3f modelForwardDir = playerNode.getWorldRotation().mult(
                Vector3f.UNIT_Z);
        Vector3f modelLeftDir = playerNode.getWorldRotation().mult(
                Vector3f.UNIT_X);
        // Depending on which nav keys are pressed, determine the change in direction

        walkDirection.set(0, 0, 0);
        if (strafeLeft) {
            walkDirection.addLocal(modelLeftDir.mult(speed));
        } else if (strafeRight) {
            walkDirection.addLocal(modelLeftDir.mult(speed).negate());
        }
        if (forward) {
            walkDirection.addLocal(modelForwardDir.mult(speed));
        } else if (backward) {
            walkDirection.addLocal(modelForwardDir.mult(speed).negate());
        }
        playerControl.setWalkDirection(walkDirection);
        // Depending on which nav keys are pressed, determine the change in rotation
        if (rotateLeft) {
            Quaternion rotateL = new Quaternion().fromAngleAxis(FastMath.PI
                    * tpf, Vector3f.UNIT_Y);
            rotateL.multLocal(viewDirection);
        } else if (rotateRight) {
            Quaternion rotateR = new Quaternion().fromAngleAxis(
                    -FastMath.PI * tpf, Vector3f.UNIT_Y);
            rotateR.multLocal(viewDirection);
        }
        playerControl.setViewDirection(viewDirection);

    }
}

Related Tutorials