Using the accelerometer

Its kinda hacky but I have the acceleromter working using the following code:



[java]

package sg.edu.sp.dmit.ANBDemo;



import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;

import android.hardware.SensorManager;

import android.os.Bundle;

import android.util.Log;



import com.jme3.app.AndroidHarness;

import com.jme3.system.android.AndroidConfigChooser.ConfigType;







public class MainActivity extends AndroidHarness implements SensorEventListener{



private SensorManager sensorManager = null;



Test20 test20;



@Override

protected void onResume() {

super.onResume();

// Register this class as a listener for the accelerometer sensor

sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);

// …and the orientation sensor

sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);

}



@Override

protected void onStop() {

// Unregister the listener

sensorManager.unregisterListener(this);

super.onStop();

}



@Override

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

}



public MainActivity() {



/*

  • https://wiki.jmonkeyengine.org/legacy/doku.php/jme3
  • run through all these to get working on android

    */



    // Set the application class to run

    //appClass = "sg.edu.sp.dmit.ANBDemo.TestBrickWall"; // brick wall native bullet

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test1"; // blue and red box

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test2"; // ninja and wall

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test3"; // flame and rock particle effects

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test4"; // teapot ** very slow to load **

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test5"; // cube flame and rock particles

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test6"; // sinbad

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test7"; // selecting objects

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test8"; // load mesh and rotate

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test9"; // rag doll

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test10"; // sky using dds file ** FAIL **

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test11"; // load scene ** FAIL

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test12"; // rag doll + flames

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test13"; // basic hud

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test14"; // navigate with touchscreen

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test15"; // select and shoot object

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test16"; // nifty gui ** FAIL ** xml parser!!

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test17"; // clickable hud buttons

    //appClass = "sg.edu.sp.dmit.ANBDemo.Test18"; // navigate with acceleramoter ** FAIL ** no input classes

    appClass = "sg.edu.sp.dmit.ANBDemo.Test20"; // clickable hud navigation buttons & accelarometer



    eglConfigType = ConfigType.BEST;



    exitDialogTitle = "Exit?";

    exitDialogMessage = "Press Yes";

    eglConfigVerboseLogging = false;



    }



    static {

    System.loadLibrary("bulletjme");

    }



    @Override

    public void onAccuracyChanged(Sensor arg0, int arg1) {

    // TODO Auto-generated method stub

    }



    @Override

    public void onSensorChanged(SensorEvent sensorEvent) {

    // wait for app to be up before firing in sensors

    if (test20==null){

    test20=(Test20) getJmeApplication();

    return;

    }

    if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

    Log.e("","Sensor 1="+Float.toString(sensorEvent.values[1]));



    if (sensorEvent.values[0]>-0.4&&sensorEvent.values[0]<0.4)

    {

    test20.movePlayer(98);

    Log.e("","STOPPING left right MOVEMENT");

    }

    if (sensorEvent.values[1]<8&&sensorEvent.values[1]>6)

    {

    test20.movePlayer(99);

    Log.e("","STOPPING UP OR DOWN MOVEMENT");

    }

    if (sensorEvent.values[0]>0.4){

    test20.movePlayer(1);

    Log.e("","Moving LEFT");

    }



    if (sensorEvent.values[0]<-0.4){



    test20.movePlayer(2);

    Log.e("","Moving Right");

    }

    if (sensorEvent.values[1]<6){



    test20.movePlayer(3);

    Log.e("","Moving Up");

    }

    if (sensorEvent.values[1]>8){



    test20.movePlayer(4);

    Log.e("","Moving Down");

    }

    }

    }

    }

    [/java]



    and



    [java]

    package sg.edu.sp.dmit.ANBDemo;



    import android.util.Log;



    import com.jme3.animation.AnimChannel;

    import com.jme3.animation.AnimControl;

    import com.jme3.animation.AnimEventListener;

    import com.jme3.animation.LoopMode;

    import com.jme3.app.SimpleApplication;

    import com.jme3.asset.AssetManager;

    import com.jme3.asset.TextureKey;

    import com.jme3.bullet.BulletAppState;

    import com.jme3.bullet.PhysicsSpace;

    import com.jme3.bullet.collision.shapes.CapsuleCollisionShape;

    import com.jme3.bullet.collision.shapes.SphereCollisionShape;

    import com.jme3.bullet.control.CharacterControl;

    import com.jme3.bullet.control.RigidBodyControl;

    import com.jme3.collision.CollisionResult;

    import com.jme3.collision.CollisionResults;

    import com.jme3.font.BitmapText;

    import com.jme3.input.KeyInput;

    import com.jme3.input.MouseInput;

    import com.jme3.input.controls.ActionListener;

    import com.jme3.input.controls.KeyTrigger;

    import com.jme3.input.controls.MouseButtonTrigger;

    import com.jme3.input.controls.TouchListener;

    import com.jme3.input.controls.TouchTrigger;

    import com.jme3.input.event.TouchEvent;

    import com.jme3.light.AmbientLight;

    import com.jme3.light.DirectionalLight;

    import com.jme3.material.Material;

    import com.jme3.math.ColorRGBA;

    import com.jme3.math.Ray;

    import com.jme3.math.Vector2f;

    import com.jme3.math.Vector3f;

    import com.jme3.renderer.Renderer;

    import com.jme3.renderer.queue.RenderQueue.ShadowMode;

    import com.jme3.scene.Geometry;

    import com.jme3.scene.Node;

    import com.jme3.scene.Spatial;

    import com.jme3.scene.shape.Box;

    import com.jme3.scene.shape.Quad;

    import com.jme3.scene.shape.Sphere;

    import com.jme3.scene.shape.Sphere.TextureMode;

    import com.jme3.texture.Texture;

    import com.jme3.texture.Texture.WrapMode;

    import com.jme3.ui.Picture;



    public class Test20 extends SimpleApplication implements TouchListener,AnimEventListener {



    Material mat;

    Material mat2;

    Material mat3;

    private static Sphere bullet;

    private static SphereCollisionShape bulletCollisionShape;



    private CharacterControl player;



    private boolean left = false, right = false, up = false, down = false;

    private Vector3f walkDirection = new Vector3f();



    private BulletAppState bulletAppState = new BulletAppState();



    @Override

    public void simpleInitApp() {



    bulletAppState = new BulletAppState();

    stateManager.attach(bulletAppState);



    bullet = new Sphere(32, 32, 0.4f, true, false);

    bullet.setTextureMode(TextureMode.Projected);

    bulletCollisionShape = new SphereCollisionShape(0.4f);



    initMaterial();



    initKeys(); // load custom key mappings



    settings.setHeight(480);

    settings.setWidth(800);



    // create my picture buttons

    Picture pic = new Picture("HUD Picture"); // up

    pic.setImage(assetManager, "Textures/ColorRamp/toon.png", true);

    pic.setWidth(80f);

    pic.setHeight(80f);

    pic.setPosition(80f, 80f);

    guiNode.attachChild(pic);



    Picture pic2 = new Picture("HUD Picture"); // down

    pic2.setImage(assetManager, "Textures/ColorRamp/toon.png", true);

    pic2.setWidth(80f);

    pic2.setHeight(80f);

    pic2.setPosition(80f, 0f);

    guiNode.attachChild(pic2);



    Picture pic3 = new Picture("HUD Picture");// left

    pic3.setImage(assetManager, "Textures/ColorRamp/toon.png", true);

    pic3.setWidth(80f);

    pic3.setHeight(80f);

    pic3.setPosition(0f, 40f);

    guiNode.attachChild(pic3);



    Picture pic4 = new Picture("HUD Picture");// right

    pic4.setImage(assetManager, "Textures/ColorRamp/toon.png", true);

    pic4.setWidth(80f);

    pic4.setHeight(80f);

    pic4.setPosition(160f, 40f);

    guiNode.attachChild(pic4);



    DirectionalLight dl = new DirectionalLight();

    dl.setDirection(new Vector3f(-0.1f, -1f, -1).normalizeLocal());

    rootNode.addLight(dl);



    createPhysicsTestWorld(rootNode, assetManager, bulletAppState.getPhysicsSpace());



    CapsuleCollisionShape capsuleShape = new CapsuleCollisionShape(1.5f, 6f, 1);

    player = new CharacterControl(capsuleShape, 0.05f);

    player.setJumpSpeed(20);

    player.setFallSpeed(30);

    player.setGravity(30);

    player.setPhysicsLocation(new Vector3f(0, 10, 0));



    bulletAppState.getPhysicsSpace().add(player);



    }



    /
    Declaring the "Shoot" action and mapping to its triggers. */

    private void initKeys() {



    inputManager.addMapping("Touch", new TouchTrigger(0));

    inputManager.addListener(this, new String[]{"Touch"});

    }

    public void movePlayer(int direction){





    switch (direction){



    case 1: // go left

    left=true;

    right=false;

    break;

    case 2: // go right

    right=true;

    left=false;

    break;

    case 3: // go up

    up=true;

    down=false;

    break;

    case 4: // go down

    down=true;

    up=false;

    break;



    case 98: // stop left or right

    right=false;

    left=false;

    break;

    case 99: // stop up or down

    up=false;

    down=false;

    break;



    default:

    break;

    }

    }



    public static void createPhysicsTestWorld(Node rootNode, AssetManager assetManager, PhysicsSpace space) {

    AmbientLight light = new AmbientLight();

    light.setColor(ColorRGBA.LightGray);

    rootNode.addLight(light);



    Material material = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");

    material.setTexture("ColorMap", assetManager.loadTexture("Interface/Logo/Monkey.jpg"));



    Box floorBox = new Box(140, 0.25f, 140);

    Geometry floorGeometry = new Geometry("Floor", floorBox);

    floorGeometry.setMaterial(material);

    floorGeometry.setLocalTranslation(0, -5, 0);

    // Plane plane = new Plane();

    // plane.setOriginNormal(new Vector3f(0, 0.25f, 0), Vector3f.UNIT_Y);

    // floorGeometry.addControl(new RigidBodyControl(new PlaneCollisionShape(plane), 0));

    floorGeometry.addControl(new RigidBodyControl(0));

    rootNode.attachChild(floorGeometry);

    space.add(floorGeometry);



    //movable boxes

    for (int i = 0; i < 12; i++) {

    Box box = new Box(0.25f, 0.25f, 0.25f);

    Geometry boxGeometry = new Geometry("Box", box);

    boxGeometry.setMaterial(material);

    boxGeometry.setLocalTranslation(i, 5, -3);

    //RigidBodyControl automatically uses box collision shapes when attached to single geometry with box mesh

    boxGeometry.addControl(new RigidBodyControl(2));

    rootNode.attachChild(boxGeometry);

    space.add(boxGeometry);

    }



    }



    public void initMaterial() {

    mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");

    TextureKey key = new TextureKey("Textures/Terrain/BrickWall/BrickWall.jpg");

    key.setGenerateMips(true);

    Texture tex = assetManager.loadTexture(key);

    tex.setWrap(WrapMode.Repeat);

    mat.setTexture("ColorMap", tex);



    mat2 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");

    TextureKey key2 = new TextureKey("Textures/Terrain/Rock/Rock.PNG");

    key2.setGenerateMips(true);

    Texture tex2 = assetManager.loadTexture(key2);

    mat2.setTexture("ColorMap", tex2);



    mat3 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");

    TextureKey key3 = new TextureKey("Textures/Terrain/Pond/Pond.jpg");

    key3.setGenerateMips(true);

    Texture tex3 = assetManager.loadTexture(key3);

    tex3.setWrap(WrapMode.Repeat);

    mat3.setTexture("ColorMap", tex3);

    }





    public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) {

    if (animName.equals("Walk")) {

    channel.setAnim("stand", 0.50f);

    channel.setLoopMode(LoopMode.DontLoop);

    channel.setSpeed(1f);

    }

    if (animName.equals("pull")) {

    channel.setAnim("stand", 0.50f);

    channel.setLoopMode(LoopMode.DontLoop);

    channel.setSpeed(1f);

    }

    if (animName.equals("Dodge")) {

    channel.setAnim("stand", 0.50f);

    channel.setLoopMode(LoopMode.DontLoop);

    channel.setSpeed(1f);

    }

    }



    @Override

    public void onTouch(String binding, TouchEvent evt, float tpf) {

    float x;

    float y;

    x = evt.getX();

    y = evt.getY();

    switch(evt.getType())

    {

    case MOVE:



    break;



    case LONGPRESSED:



    Geometry bulletg = new Geometry("bullet", bullet);

    bulletg.setMaterial(mat2);

    bulletg.setShadowMode(ShadowMode.CastAndReceive);

    bulletg.setLocalTranslation(cam.getLocation());

    bulletg.setLocalTranslation(bulletg.getLocalTranslation().x, bulletg.getLocalTranslation().y, bulletg.getLocalTranslation().z-20f);



    SphereCollisionShape bulletCollisionShape = new SphereCollisionShape(0.4f);

    RigidBodyControl bulletNode = new RigidBodyControl(bulletCollisionShape, 1);

    bulletNode.setLinearVelocity(cam.getDirection().mult(25));

    bulletg.addControl(bulletNode);

    rootNode.attachChild(bulletg);

    bulletAppState.getPhysicsSpace().add(bulletNode);

    break;



    case TAP:



    break;



    case DOWN:



    if (x>80&&x<160&&y>80&&y<160){

    Log.e("","You touched " + x + " " + y + " which is button 1!"); //up



    up=true;

    }

    if (x>80&&x<160&&y>0&&y<80){

    Log.e("","You touched " + x + " " + y + " which is button 2!"); //down

    down=true;

    }

    if (x>0&&x<80&&y>40&&y<120){

    Log.e("","You touched " + x + " " + y + " which is button 3!"); //left

    left=true;



    }



    if (x>160&&x<240&&y>40&&y<120){

    Log.e("","You touched " + x + " " + y + " which is button 4!");//right



    right=true;



    }





    break;



    case UP:



    up=false;

    down=false;

    right=false;

    left=false;



    break;



    case FLING:







    break;



    default:



    break;

    }

    Log.e("","Event Type " + evt.getType() + " x="+x+" y="+y);

    evt.setConsumed();





    }



    public void simpleUpdate(float tpf) {



    Vector3f camDir = cam.getDirection().clone().multLocal(0.6f);

    Vector3f camLeft = cam.getLeft().clone().multLocal(0.4f);



    walkDirection.set(0, 0, 0);

    if (left) { walkDirection.addLocal(camLeft); }

    if (right) { walkDirection.addLocal(camLeft.negate()); }

    if (up) { walkDirection.addLocal(camDir); }

    if (down) { walkDirection.addLocal(camDir.negate()); }

    player.setWalkDirection(walkDirection);

    cam.setLocation(player.getPhysicsLocation());

    }



    @Override

    public void onAnimChange(AnimControl arg0, AnimChannel arg1, String arg2) {

    // TODO Auto-generated method stub



    }

    }

    [/java]
4 Likes

using test20=(Test20) getJmeApplication();



lets you hook into the simpleapplication and in theory you could use the gesture recogniser

http://developer.android.com/resources/articles/gestures.html

and/or event voice control

http://developer.android.com/resources/articles/speech-input.html



I’m thinking for the voice recognition - commands to a virtual 3d pet etc.

2 Likes

oh sweet, thanks i will be stealing this :slight_smile:

Itersting code, right now im trying to create hello world in android.



I´ve been able to compile the begginers tutoriales in my mobile, the problem comes when i try to use advance fetures with android.



I have to create an alternative way for the proyect. In my test expierence i use the option to use as an android application changing it from mobile option in project properties.



Should i create the project in an alternative way as it explain in this post to use android options?



http://hub.jmonkeyengine.org/groups/android/forum/topic/how-to-run-your-jme3-application-on-android-androidharness/



Thanks.

PD. Here is the error that i get when i try to compile the code.



Building jar: C:UsersJohanDocumentsJmonkeyHolaAcelerometrobuildassets.jar

init:

deps-jar:

Updating property file: C:UsersJohanDocumentsJmonkeyHolaAcelerometrobuildbuilt-jar.properties

Created dir: C:UsersJohanDocumentsJmonkeyHolaAcelerometrobuildclasses

Created dir: C:UsersJohanDocumentsJmonkeyHolaAcelerometrobuildempty

Compiling 1 source file to C:UsersJohanDocumentsJmonkeyHolaAcelerometrobuildclasses

warning: [options] bootstrap class path not set in conjunction with -source 1.5

C:UsersJohanDocumentsJmonkeyHolaAcelerometrosrcmygameMain.java:3: error: package android.util does not exist

import android.util.Log;

C:UsersJohanDocumentsJmonkeyHolaAcelerometrosrcmygameMain.java:279: error: cannot find symbol

Log.e("", “You touched " + x + " " + y + " which is button 1!”); //up

symbol: variable Log

location: class Main

C:UsersJohanDocumentsJmonkeyHolaAcelerometrosrcmygameMain.java:284: error: cannot find symbol

Log.e("", “You touched " + x + " " + y + " which is button 2!”); //down

symbol: variable Log

location: class Main

C:UsersJohanDocumentsJmonkeyHolaAcelerometrosrcmygameMain.java:288: error: cannot find symbol

Log.e("", “You touched " + x + " " + y + " which is button 3!”); //left

symbol: variable Log

location: class Main

C:UsersJohanDocumentsJmonkeyHolaAcelerometrosrcmygameMain.java:294: error: cannot find symbol

Log.e("", “You touched " + x + " " + y + " which is button 4!”);//right

symbol: variable Log

location: class Main

C:UsersJohanDocumentsJmonkeyHolaAcelerometrosrcmygameMain.java:319: error: cannot find symbol

Log.e("", “Event Type " + evt.getType() + " x=” + x + " y=" + y);

symbol: variable Log

location: class Main

6 errors

1 warning

C:UsersJohanDocumentsJmonkeyHolaAcelerometronbprojectbuild-impl.xml:596: The following error occurred while executing this line:

C:UsersJohanDocumentsJmonkeyHolaAcelerometronbprojectbuild-impl.xml:281: Compile failed; see the compiler error output for details.

BUILD FAILED (total time: 1 second)

Ok solved, iv just comment the

//import android.util.Log;



and all other lines that use the Android Log in the jmoney Main code.



Change in MainActivity the



appClass = “sg.edu.sp.dmit.ANBDemo.Test20”; // clickable hud navigation buttons & accelarometer



to



appClass = “mygame.Main”; // clickable hud navigation buttons & accelarometer



and add the import



import mygame.Main;

Exactly, this class doesn’t properly separate android and jme code so it can only be used on android and not with a normal platform-independent jme project:

https://wiki.jmonkeyengine.org/legacy/doku.php/jme3:android#using_android_specific_functions

1 Like