From 47c43078f081e8ddf6468f1ef3492478383e40c6 Mon Sep 17 00:00:00 2001 From: Daniel Collin Date: Wed, 11 Mar 2009 14:56:11 +0000 Subject: [PATCH] now we can steer the ship --- src/sg/SpaceGame.java | 106 ++---------- src/sg/SpaceGame2.java | 230 ++++++++++++--------------- src/sg/input/FirstPersonHandler.java | 65 +++++++- 3 files changed, 182 insertions(+), 219 deletions(-) diff --git a/src/sg/SpaceGame.java b/src/sg/SpaceGame.java index 8cc7d04..256930c 100644 --- a/src/sg/SpaceGame.java +++ b/src/sg/SpaceGame.java @@ -1,28 +1,12 @@ package sg; -import java.util.logging.Level; -import java.util.logging.Logger; - import sg.env.Environment; +import sg.input.FirstPersonHandler; import sg.util.SGUtil; -import com.jme.bounding.BoundingBox; import com.jme.scene.Node; -import com.jme.scene.shape.Sphere; -import com.jme.scene.state.TextureState; -import com.jme.system.DisplaySystem; -import com.jme.image.Texture; -import com.jme.input.ChaseCamera; -import com.jme.input.InputHandler; -import com.jme.input.KeyInput; -import com.jme.input.action.InputAction; -import com.jme.input.action.InputActionEvent; -import com.jme.math.Quaternion; import com.jme.math.Vector3f; -import com.jme.util.TextureManager; import com.jmex.physics.DynamicPhysicsNode; -import com.jmex.physics.PhysicsSpace; -import com.jmex.physics.PhysicsUpdateCallback; import com.jmex.physics.StaticPhysicsNode; import com.jmex.physics.util.SimplePhysicsGame; @@ -30,7 +14,9 @@ public class SpaceGame extends SimplePhysicsGame { private StaticPhysicsNode staticNode; private DynamicPhysicsNode dynamicNode; private Environment environment; - private InputHandler physicsStepInputHandler; + private Node ship; + private DynamicPhysicsNode shipNode; + private FirstPersonHandler firstPersonHandler; public static void main(String[] args) { //Logger.getLogger("").setLevel( Level.WARNING ); @@ -48,91 +34,27 @@ public class SpaceGame extends SimplePhysicsGame { rootNode.attachChild(staticNode); dynamicNode = getPhysicsSpace().createDynamicNode(); rootNode.attachChild(dynamicNode); + shipNode = getPhysicsSpace().createDynamicNode(); + rootNode.attachChild(shipNode); //environment - environment = new Environment(); + environment = new Environment(rootNode); rootNode.attachChild(environment); //light //TODO - //controll - physicsStepInputHandler = new InputHandler(); - getPhysicsSpace().addToUpdateCallbacks( new PhysicsUpdateCallback() { - public void beforeStep( PhysicsSpace space, float time ) { - physicsStepInputHandler.update( time ); - } - public void afterStep( PhysicsSpace space, float time ) { - - } - } ); - physicsStepInputHandler.addAction( new MyInputAction(700, MyInputAction.FORWARD), - InputHandler.DEVICE_KEYBOARD, KeyInput.KEY_HOME, InputHandler.AXIS_NONE, true ); - physicsStepInputHandler.addAction( new MyInputAction(700, MyInputAction.BACK), - InputHandler.DEVICE_KEYBOARD, KeyInput.KEY_END, InputHandler.AXIS_NONE, true ); - physicsStepInputHandler.addAction( new MyInputAction(700, MyInputAction.LEFT), - InputHandler.DEVICE_KEYBOARD, KeyInput.KEY_PGUP, InputHandler.AXIS_NONE, true ); - physicsStepInputHandler.addAction( new MyInputAction(700, MyInputAction.RIGHT), - InputHandler.DEVICE_KEYBOARD, KeyInput.KEY_PGDN, InputHandler.AXIS_NONE, true ); - - //sphere - /* - Sphere s = new Sphere("Sphere", 10, 10, 25); - s.setLocalTranslation(new Vector3f(0,0,-40)); - s.setModelBound(new BoundingBox()); - s.updateModelBound(); - Texture texture = TextureManager.loadTexture( - SpaceGame.class.getClassLoader().getResource( - "jmetest/data/images/Monkey.jpg"), - Texture.MinificationFilter.BilinearNearestMipMap, - Texture.MagnificationFilter.Bilinear); - TextureState ts = display.getRenderer().createTextureState(); - ts.setEnabled(true); - ts.setTexture(texture); - s.setRenderState(ts); - dynamicNode.attachChild(s); - */ - - Node ship = SGUtil.loadModel("sg/data/models/ships/G6.3ds"); + //ship + ship = SGUtil.loadModel("sg/data/models/ships/G6.3ds"); ship.setLocalTranslation(new Vector3f(0,0,-40)); - dynamicNode.attachChild(ship); - - //ChaseCamera ccam = new ChaseCamera( cam, ship); - //input = ccam; + shipNode.attachChild(ship); + + //controll + firstPersonHandler = new FirstPersonHandler(ship, shipNode, cam); } public void simpleUpdate(){ environment.update(); - } - - private class MyInputAction extends InputAction { - public static final int FORWARD = 1; - public static final int BACK = 2; - public static final int LEFT = 3; - public static final int RIGHT = 4; - private final float force; - private final Vector3f appliedForce = new Vector3f(); - private Vector3f rotation; - private final int direction; - - public MyInputAction(float force, int direction) { - this.force = force; - this.direction = direction; - } - - public void performAction( InputActionEvent evt ) { - rotation = dynamicNode.getLocalRotation().getRotationColumn(2); - switch(direction){ - case 1: - case 2: - appliedForce.set(rotation.mult(force)).multLocal( evt.getTime() ); - dynamicNode.addForce(appliedForce); - break; - case 3: - break; - case 4: - break; - } - } + firstPersonHandler.update(0.1f); } } \ No newline at end of file diff --git a/src/sg/SpaceGame2.java b/src/sg/SpaceGame2.java index 41f8224..c90c600 100644 --- a/src/sg/SpaceGame2.java +++ b/src/sg/SpaceGame2.java @@ -24,163 +24,141 @@ import com.jmex.game.state.GameStateManager; public class SpaceGame2 extends BaseGame { private static final Logger logger = Logger.getLogger(SpaceGame2.class.getName()); - public static final String TITLE = "SpaceGame"; - - /** Time per frame */ - protected float tpf; - /** High resolution timer for jME. */ - protected Timer timer; - + protected float tpf; //Time per frame + protected Timer timer; //High resolution timer for jME. + public static void main(String[] args) { SpaceGame2 game = new SpaceGame2(); game.setConfigShowMode(ConfigShowMode.AlwaysShow); game.start(); } - /** - * Creates display, sets up camera, and binds keys. Called in - * BaseGame.start() directly after the dialog box. - * - * @see AbstractGame#initSystem() - */ - protected void initSystem() throws JmeException { - logger.info(getVersion()); - try { - /** - * Get a DisplaySystem acording to the renderer selected in the - * startup box. - */ - display = DisplaySystem.getDisplaySystem(settings.getRenderer() ); - - // Alpha bits to use for the renderer. Any changes must be made prior to call of start(). - display.setMinAlphaBits( 0 ); - // Depth bits to use for the renderer. Any changes must be made prior to call of start(). - display.setMinDepthBits( 8 ); - // Stencil bits to use for the renderer. Any changes must be made prior to call of start(). - display.setMinStencilBits( 0 ); - // Number of samples to use for the multisample buffer. Any changes must be made prior to call of start(). - display.setMinSamples( 0 ); + /** + * Creates display, sets up camera, and binds keys. Called in + * BaseGame.start() directly after the dialog box. + * @see AbstractGame#initSystem() + */ + protected void initSystem() throws JmeException { + logger.info(getVersion()); + try { + /** + * Get a DisplaySystem acording to the renderer selected in the + * startup box. + */ + display = DisplaySystem.getDisplaySystem(settings.getRenderer() ); - /** Create a window with the startup box's information. */ - display.createWindow(settings.getWidth(), settings.getHeight(), - settings.getDepth(), settings.getFrequency(), - settings.isFullscreen() ); - logger.info("Running on: " + display.getAdapter() - + "\nDriver version: " + display.getDriverVersion() + "\n" - + display.getDisplayVendor() + " - " - + display.getDisplayRenderer() + " - " - + display.getDisplayAPIVersion()); + // Alpha bits to use for the renderer. Any changes must be made prior to call of start(). + display.setMinAlphaBits( 0 ); + // Depth bits to use for the renderer. Any changes must be made prior to call of start(). + display.setMinDepthBits( 8 ); + // Stencil bits to use for the renderer. Any changes must be made prior to call of start(). + display.setMinStencilBits( 0 ); + // Number of samples to use for the multisample buffer. Any changes must be made prior to call of start(). + display.setMinSamples( 0 ); + + /** Create a window with the startup box's information. */ + display.createWindow(settings.getWidth(), settings.getHeight(), + settings.getDepth(), settings.getFrequency(), + settings.isFullscreen() ); + logger.info("Running on: " + display.getAdapter() + + "\nDriver version: " + display.getDriverVersion() + "\n" + + display.getDisplayVendor() + " - " + + display.getDisplayRenderer() + " - " + + display.getDisplayAPIVersion()); - } catch ( JmeException e ) { - /** - * If the displaysystem can't be initialized correctly, exit - * instantly. - */ - logger.log(Level.SEVERE, "Could not create displaySystem", e); - System.exit( 1 ); - } + } catch ( JmeException e ) { + //If the displaysystem can't be initialized correctly, exit instantly. + logger.log(Level.SEVERE, "Could not create displaySystem", e); + System.exit( 1 ); + } - /** Set a black background. */ - display.getRenderer().setBackgroundColor( ColorRGBA.black.clone() ); + display.getRenderer().setBackgroundColor( ColorRGBA.black.clone() ); //Set a black background. - /** Get a high resolution timer for FPS updates. */ - timer = Timer.getTimer(); - - GameStateManager.create(); - KeyBindingManager manager = KeyBindingManager.getKeyBindingManager(); - manager.set("mem_report", KeyInput.KEY_TAB); - manager.set("exit", KeyInput.KEY_ESCAPE); + timer = Timer.getTimer(); //Get a high resolution timer for FPS updates. - /** Sets the title of our display. */ - display.setTitle( TITLE ); + GameStateManager.create(); + KeyBindingManager manager = KeyBindingManager.getKeyBindingManager(); + manager.set("mem_report", KeyInput.KEY_TAB); + manager.set("exit", KeyInput.KEY_ESCAPE); - } + display.setTitle( TITLE ); //Sets the title of our display. + + } @Override protected void initGame() { GameStateManager.getInstance().cleanup(); GameStateManager.getInstance().attachChild(new MenuState("menu")); GameStateManager.getInstance().attachChild(new InGameState("ingame")); - + timer.reset(); } @Override protected void update(float interpolation) { - /** Recalculate the framerate. */ - timer.update(); - /** Update tpf to time per frame according to the Timer. */ - tpf = timer.getTimePerFrame(); - - // Execute updateQueue item - GameTaskQueueManager.getManager().getQueue(GameTaskQueue.UPDATE).execute(); + timer.update(); //Recalculate the framerate. + tpf = timer.getTimePerFrame(); //Update tpf to time per frame according to the Timer. + // Execute updateQueue item + GameTaskQueueManager.getManager().getQueue(GameTaskQueue.UPDATE).execute(); GameStateManager.getInstance().update(tpf); - - - if ( KeyBindingManager.getKeyBindingManager().isValidCommand( - "mem_report", false ) ) { - long totMem = Runtime.getRuntime().totalMemory(); - long freeMem = Runtime.getRuntime().freeMemory(); - long maxMem = Runtime.getRuntime().maxMemory(); - - logger.info("|*|*| Memory Stats |*|*|"); - logger.info("Total memory: "+(totMem>>10)+" kb"); - logger.info("Free memory: "+(freeMem>>10)+" kb"); - logger.info("Max memory: "+(maxMem>>10)+" kb"); - } - if ( KeyBindingManager.getKeyBindingManager().isValidCommand( "exit", - false ) ) { - finish(); - } + + if ( KeyBindingManager.getKeyBindingManager().isValidCommand("mem_report", false ) ) { + long totMem = Runtime.getRuntime().totalMemory(); + long freeMem = Runtime.getRuntime().freeMemory(); + long maxMem = Runtime.getRuntime().maxMemory(); + + logger.info("|*|*| Memory Stats |*|*|"); + logger.info("Total memory: "+(totMem>>10)+" kb"); + logger.info("Free memory: "+(freeMem>>10)+" kb"); + logger.info("Max memory: "+(maxMem>>10)+" kb"); + } + if ( KeyBindingManager.getKeyBindingManager().isValidCommand( "exit", false ) ) { + finish(); + } + } + + /** + * Clears stats, the buffers and renders bounds and normals if on. + * @param interpolation unused in this implementation + * @see AbstractGame#render(float interpolation) + */ + protected void render( float interpolation ) { + Renderer r = display.getRenderer(); + r.clearBuffers(); //Clears the previously rendered information. + + // Execute renderQueue item + GameTaskQueueManager.getManager().getQueue(GameTaskQueue.RENDER).execute(); + GameStateManager.getInstance().render(tpf); } - - /** - * Clears stats, the buffers and renders bounds and normals if on. - * - * @param interpolation unused in this implementation - * @see AbstractGame#render(float interpolation) - */ - protected void render( float interpolation ) { - Renderer r = display.getRenderer(); - /** Clears the previously rendered information. */ - r.clearBuffers(); - - // Execute renderQueue item - GameTaskQueueManager.getManager().getQueue(GameTaskQueue.RENDER).execute(); - - GameStateManager.getInstance().render(tpf); - } @Override protected void reinit() { - - } - - /** - * Cleans up the keyboard. - * - * @see AbstractGame#cleanup() - */ - protected void cleanup() { - logger.info( "Cleaning up resources." ); - TextureManager.doTextureCleanup(); - if (display != null && display.getRenderer() != null) - display.getRenderer().cleanup(); - KeyInput.destroyIfInitalized(); - MouseInput.destroyIfInitalized(); - JoystickInput.destroyIfInitalized(); - } - - /** - * Calls the quit of BaseGame to clean up the display and then closes the JVM. - */ - protected void quit() { - super.quit(); - System.exit( 0 ); - } + } + + /** + * Cleans up the keyboard. + * @see AbstractGame#cleanup() + */ + protected void cleanup() { + logger.info( "Cleaning up resources." ); + TextureManager.doTextureCleanup(); + if (display != null && display.getRenderer() != null) + display.getRenderer().cleanup(); + KeyInput.destroyIfInitalized(); + MouseInput.destroyIfInitalized(); + JoystickInput.destroyIfInitalized(); + } + + /** + * Calls the quit of BaseGame to clean up the display and then closes the JVM. + */ + protected void quit() { + super.quit(); + System.exit( 0 ); + } } \ No newline at end of file diff --git a/src/sg/input/FirstPersonHandler.java b/src/sg/input/FirstPersonHandler.java index 5544978..e5683c5 100644 --- a/src/sg/input/FirstPersonHandler.java +++ b/src/sg/input/FirstPersonHandler.java @@ -1,12 +1,75 @@ package sg.input; +import com.jme.input.KeyBindingManager; +import com.jme.input.KeyInput; +import com.jme.math.FastMath; +import com.jme.math.Quaternion; +import com.jme.math.Vector3f; import com.jme.renderer.Camera; import com.jme.scene.Node; +import com.jmex.physics.DynamicPhysicsNode; public class FirstPersonHandler extends GlobalInputHandler{ + private final Vector3f appliedForce = new Vector3f(); + private Vector3f rotation; + private Quaternion qRot = new Quaternion(); + private float xAngle, yAngle, zAngle; + private Node ship; + private DynamicPhysicsNode shipNode; + private Camera cam; - public FirstPersonHandler(Node ship, Camera cam){ + public FirstPersonHandler(Node ship, DynamicPhysicsNode shipNode, Camera cam){ + this.ship = ship; + this.shipNode = shipNode; + this.cam = cam; + KeyBindingManager manager = KeyBindingManager.getKeyBindingManager(); + manager.set("yaw", KeyInput.KEY_K); + manager.set("yaw2", KeyInput.KEY_I); + manager.set("roll", KeyInput.KEY_U); + manager.set("roll2", KeyInput.KEY_O); + manager.set("pitch", KeyInput.KEY_J); + manager.set("pitch2", KeyInput.KEY_L); + manager.set("forw", KeyInput.KEY_2); + manager.set("backw", KeyInput.KEY_1); + } + + public void update(float time){ + super.update(time); + if ( KeyBindingManager.getKeyBindingManager().isValidCommand("yaw", true ) ) { + xAngle = (xAngle + 0.05f) % (2*FastMath.PI); + ship.setLocalRotation(qRot.fromAngles(xAngle, yAngle, zAngle)); + } + if ( KeyBindingManager.getKeyBindingManager().isValidCommand("yaw2", true ) ) { + xAngle = (xAngle - 0.05f) % (2*FastMath.PI); + ship.setLocalRotation(qRot.fromAngles(xAngle, yAngle, zAngle)); + } + if ( KeyBindingManager.getKeyBindingManager().isValidCommand("roll", true ) ) { + yAngle = (yAngle + 0.05f) % (2*FastMath.PI); + ship.setLocalRotation(qRot.fromAngles(xAngle, yAngle, zAngle)); + } + if ( KeyBindingManager.getKeyBindingManager().isValidCommand("roll2", true ) ) { + yAngle = (yAngle - 0.05f) % (2*FastMath.PI); + ship.setLocalRotation(qRot.fromAngles(xAngle, yAngle, zAngle)); + } + if ( KeyBindingManager.getKeyBindingManager().isValidCommand("pitch", true ) ) { + zAngle = (zAngle + 0.05f) % (2*FastMath.PI); + ship.setLocalRotation(qRot.fromAngles(xAngle, yAngle, zAngle)); + } + if ( KeyBindingManager.getKeyBindingManager().isValidCommand("pitch2", true ) ) { + zAngle = (zAngle - 0.05f) % (2*FastMath.PI); + ship.setLocalRotation(qRot.fromAngles(xAngle, yAngle, zAngle)); + } + if ( KeyBindingManager.getKeyBindingManager().isValidCommand("forw", true ) ) { + rotation = ship.getLocalRotation().getRotationColumn(2); + appliedForce.set(rotation.mult(-700)).multLocal(time); + shipNode.addForce(appliedForce); + } + if ( KeyBindingManager.getKeyBindingManager().isValidCommand("backw", true ) ) { + rotation = ship.getLocalRotation().getRotationColumn(2); + appliedForce.set(rotation.mult(700)).multLocal(time); + shipNode.addForce(appliedForce); + } } }