1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
package com.example.capteurskegtux;
import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.hardware.*;
import android.os.Bundle;
import android.view.*;
public class CopyOfCapteursBoule extends Activity implements SensorEventListener {
private SensorManager gestionCapteurs;
private Sensor accelerometre;
private SurfaceView surface;
private SurfaceHolder holder;
private Bitmap boule, fond;
private float bx, by, vx, vy, tx, ty;
public Context c;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boule = BitmapFactory.decodeResource(getResources(), R.drawable.boule);
fond = BitmapFactory.decodeResource(getResources(), R.drawable.fonecran);
surface = new SurfaceView(this);
holder = surface.getHolder();
gestionCapteurs = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometre = gestionCapteurs.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
setContentView(surface);
}
@Override
protected void onStart() {
super.onStart();
gestionCapteurs.registerListener(this, accelerometre, SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onStop() {
super.onStop();
gestionCapteurs.unregisterListener(this, accelerometre);
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
public void onSensorChanged(SensorEvent evt) {
if (evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// Ajout les valeurs du capteur aux variables
vx -= evt.values[0];
vy += evt.values[1];
// Déplacement de la boule
bx += vx;
by += vy;
// Récupération de la taille de l'écran
tx = surface.getWidth() - boule.getWidth();
ty = surface.getHeight() - boule.getHeight();
// Empêcher la boule de sortir
if (bx<0) { bx = 0; vx = 0; }
if (by<0) { by = 0; vy = 0; }
if (bx>tx) { bx = tx; vx = 0; }
if (by>ty) { by = ty; vy = 0; }
// Redessiner
Canvas dessin = holder.lockCanvas();
if (dessin==null) return;
dessin.drawBitmap(fond, 0, 0, null);
dessin.drawBitmap(boule, bx, by, null);
holder.unlockCanvasAndPost(dessin);
}
}
public void onAccuracyChanged(Sensor capteur, int precision) { }
} |
Partager