I'm creating a Java app with my friend, and wanted to put an image with accelerometer that would move across the screen by deflecting the obstacles, but I have a problem with the video I've seen (the only one I've found) that does this leaves a strange function and I do not know what to do anymore.
This is the code I'm having problems with:
package softs.gustavo.game;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Created by Gustavo on 02/03/2016.
*/
public class MoveMago extends AppCompatActivity implements SensorEventListener{
Bitmap magao = BitmapFactory.decodeResource(getResource(), R.drawable.magao);
SensorManager sm;
Mago ourView;
Float x,y,sensorX,sensorY;
private Bundle savedInstanceState;
@Override
public void onSensorChanged(SensorEvent event) {
try{
Thread.sleep(20);
}catch (InterruptedException e){
e.printStackTrace();
}
sensorX = event.values[0];
sensorY = event.values[1];
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public class Mago extends SurfaceView implements Runnable{
SurfaceHolder ourHolder;
Thread ourThread =null;
boolean isRunning = true;
public Mago(Context context){
super(context);
ourHolder = getHolder();
}
public void pause(){
isRunning = false;
while (true){
try {
ourThread.join();
} catch (InterruptedException e){
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume(){
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
@Override
public void run() {
while (isRunning){
if(!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(magao, sensorX*10, sensorY, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size() != 0) ;
//setup a sensor
Sensor s = sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
}
magao = BitmapFactory.decodeResource(getResource(),R.drawable.magao);
x = y = sensorX = sensorY = 0;
ourView = new MoveMago(this);
ourView.resume();
setContentView(ourView);
}