Game-Apps für Smartphones und Tablets |
|
Bern University oh Teacher Education |
Man erzeugt einen GGComboSensor-Objekt und implementiert einen GGCombosensorListener, mit den Callbackmethoden orientationChanged(), accelerationChanged() und magneticFieldChanged(). Die Methode orientationChanged() gibt das Azimut zurück. Der Winkelgrösse wird in der Statuszeile angezeigt und das Compassbild dreht sich in die entsprechende Richtung. Um das Bild in allen möglichen Drehpositionen darzustellen, wird das Bild als GGBitmap erfasst, die genaue Position des Bildes berechnet und angezeigt. |
![]() |
|
Programmcode:
// Compass.java package app.compass; import ch.aplu.android.*; import android.graphics.*; public class Compass extends GameGrid implements GGComboSensorListener { private final String title = "Compass Demo"; private final int titleHeight = 50; private final int statusHeight = 40; private GGTextField tfTitle; private GGTextField tfStatus; private int screenWidth; private int screenHeight; private int xCenter; private int yCenter; private Actor compass; private Bitmap compassSeed; public Compass() { super(WHITE, windowZoom(400)); } public void main() { screenWidth = getNbHorzCells(); screenHeight = getNbVertCells(); xCenter = screenWidth / 2; yCenter = screenHeight / 2; initDisplay(); compassSeed = new Actor("compass").getImage(); GGComboSensor sensor = GGComboSensor.init(this); sensor.addComboSensorListener(this); } private void initDisplay() { GGBackground bg = getBg(); bg.clear(Color.WHITE); bg.setPaintColor(Color.GRAY); bg.fillRectangle(new Point(1, 1), new Point(screenWidth - 1, titleHeight)); bg.fillRectangle(new Point(1, screenHeight - statusHeight), new Point(screenWidth - 1, screenHeight - 1)); bg.setPaintColor(Color.WHITE); tfTitle = new GGTextField(title, new Location(0, 0), false); int w = tfTitle.getTextWidth(); tfTitle.setLocation(new Location((screenWidth - w) / 2, titleHeight / 2)); tfTitle.show(); tfStatus = new GGTextField(new Location(10, screenHeight - statusHeight / 2), false); tfStatus.show(); bg.setPaintColor(Color.BLACK); int r = 150; bg.drawLine(new Point(xCenter, yCenter - r), new Point(xCenter, yCenter + r)); bg.drawLine(new Point(xCenter - r, yCenter), new Point(xCenter + r, yCenter)); refresh(); } private void showStatus(String text) { tfStatus.setText(text); } public void orientationChanged(double[] values) { int azimuth = (int)values[3]; showStatus("Azimuth = " + azimuth + " degrees"); if (compass != null) compass.removeSelf(); compass = new Actor(GGBitmap.getRotatedImage(compassSeed, -azimuth)); addActor(compass, new Location(xCenter, yCenter)); } public void accelerationChanged(double[] values) { } public void magneticFieldChanged(double[] values) { } } |