我已經完成了開發一個示例應用程序的幫助,在網上發佈的教程。我的目標是訪問加速度計並根據手機方向移動一個球。我成功地證明了程度。但我有兩個issesAndroid加速度計移動球
- 球是走出去的束縛屏幕
- 球運動的不順利(看起來消失,重新出現在屏幕上)
這裏是我的碼。我們需要做些什麼改變才能讓球順利,精確地運動,就像我們在很多比賽中看到的那樣。
public class Accelerometer extends Activity implements SensorEventListener{
/** Called when the activity is first created. */
CustomDrawableView mCustomDrawableView = null;
ShapeDrawable mDrawable = new ShapeDrawable();
public static int x;
public static int y;
private Bitmap mBitmap;
private Bitmap mWood;
private SensorManager sensorManager = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get a reference to a SensorManager
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mCustomDrawableView = new CustomDrawableView(this);
setContentView(mCustomDrawableView);
// setContentView(R.layout.main);
}
// This method will update the UI on new sensor events
public void onSensorChanged(SensorEvent sensorEvent)
{
{
/* if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// the values you were calculating originally here were over 10000!
x = (int) Math.pow(sensorEvent.values[0], 2);
y = (int) Math.pow(sensorEvent.values[1], 2);
}*/
if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
Display display = getWindowManager().getDefaultDisplay();
int xmax = display.getWidth();
int ymax = display.getHeight();
x = (int) Math.pow(sensorEvent.values[1], 2);
y = (int) Math.pow(sensorEvent.values[2], 2);
if (x > xmax) {
x = xmax;
} else if (x < -xmax) {
x = -xmax;
}
if (y > ymax) {
y = ymax;
} else if (y < -ymax) {
y = -ymax;
}
}
}
}
// I've chosen to not implement this method
public void onAccuracyChanged(Sensor arg0, int arg1)
{
// TODO Auto-generated method stub
}
@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_GAME);
// ...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();
}
public class CustomDrawableView extends View
{
public CustomDrawableView(Context context)
{
super(context);
Bitmap ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
final int dstWidth = 50;
final int dstHeight = 50;
mBitmap = Bitmap.createScaledBitmap(ball, dstWidth, dstHeight, true);
mWood = BitmapFactory.decodeResource(getResources(), R.drawable.wood);
}
protected void onDraw(Canvas canvas)
{
final Bitmap bitmap = mBitmap;
canvas.drawBitmap(mWood, 0, 0, null);
canvas.drawBitmap(bitmap, x, y, null);
invalidate();
}
}
}
..完美匹配您正在尋找的是[這裏](http://www.appsrox.com/android/tutorials/accelerometer-golf/) – user2230793