0
\$\begingroup\$

I created a class for accelerometer, and there are no errors, my game does not crash when I run it, but my character does not move when I tilt my phone. I have been trying to figure out how to use the accelerometer for some days now, but every tutorial uses it in an activity, and there is no activity in my application.

Here is the code:

package com.saladchef.bananasplit;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class MyAccelerometerClass implements SensorEventListener {
private SensorManager sensorManager;

public float x, y, z;

public MyAccelerometerClass(Context context) {
    sensorManager = (SensorManager) context
            .getSystemService(Context.SENSOR_SERVICE);
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub

}

@Override
public void onSensorChanged(SensorEvent event) {
    x = event.values[0];
    y = event.values[1];
    z = event.values[2];

    if (y == 0.0){
        Banana.stop();
    }
    if(y >= 1.5){
        Banana.moveRight();
    }

    if (y <= -1.5){
        Banana.moveLeft();
    }


}

public SensorManager getSensorManager() {
    return sensorManager;
}

public void setSensorManager(SensorManager sensorManager) {
    this.sensorManager = sensorManager;
}

public float getX() {
    return x;
}

public void setX(float x) {
    this.x = x;
}

public float getY() {
    return y;
}

public void setY(float y) {
    this.y = y;
}

public float getZ() {
    return z;
}

public void setZ(float z) {
    this.z = z;
}

// codes

}

\$\endgroup\$
  • \$\begingroup\$ I just want to point out that the accelerometer orientations is set up with the devices default orientation and does not change as the device is rotated. That is, phone default orientation is usually portrait, and tablets is usually landscape. If not handled properly your character might be moving up and down instead of left and right on some devices. \$\endgroup\$ – Aholio Aug 7 '14 at 0:43
1
\$\begingroup\$

You need to register listener and get sensor, see official site.

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);



@Override
  protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this);
  }
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.