我已经编写了一个代码来借助 android 中的加速度计移动一个球,这样如果它触及 4 个边缘中的任何一个,它就会重新出现在对面的边缘上,我的问题是
1.ball 没有重新出现在对边 2.orientation 改变为 lanscape
这是我的代码
public class Accelerate extends Activity implements SensorEventListener {
float x, y, sensorX, sensorY, a, b, centerX, centerY;
Bitmap ball;
SensorManager sm;
NixSurface ourSurfaceView;
public class NixSurface extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public NixSurface(Context context) {
super(context);
ourHolder = getHolder();
}
public void pause() {
isRunning = false;
while (true) {
try {
ourThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume() {
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawRGB(255, 255, 255);
centerX = canvas.getWidth() / 2;
centerY = canvas.getHeight() / 2;
x += sensorX;
y += sensorY;
a = centerX + x;
b = centerY + y;
if (a > canvas.getWidth())
a = 0;
if (b > canvas.getHeight())
b = 0;
if (a < 0)
a = canvas.getWidth();
if (b < 0)
b = canvas.getHeight();
canvas.drawBitmap(ball, a, b, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size() != 0) {
Sensor s = sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
}
x = y = sensorY = sensorX = 0;
ball = BitmapFactory.decodeResource(getResources(), R.drawable.nix);
ourSurfaceView = new NixSurface(this);
ourSurfaceView.resume();
setContentView(ourSurfaceView);
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
sm.unregisterListener(this);
super.onStop();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
// nothing to do here
}
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
try {
Thread.sleep(16);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sensorX = -event.values[0];
sensorY = event.values[1];
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}