Android game programming-accelerator and compass Testing

Source: Internet
Author: User

The following are all converted from the android game programming entry-level classic. For more information, see the source.

An interesting input method in the game is the accelerator. All Android devices require a 3D accelerator. Also, the compass function can sense the magnetic field direction and the mobile phone pitch angle.

To obtain the accelerometer information, we register a listener. The interface to be implemented is sensoreventlistener, which has two methods:

Public void onsensorchanged (sensorevent event );

Public void onaccuracychanged (sensor, int accuracy );

The first method is called when a new accelerometer event occurs, and the second method is called when the accuracy of the accelerometer changes. In general, we can safely ignore the second method.

To implement this function, we first need to confirm whether there is an accelerator on the device. Although all Android devices should have an accelerator, it may change in the future. Make sure that the input method is available.

First, we need to obtain a sensormanager instance, which will indicate whether the accelerator meter is installed on the device and where to register the listener. You can use the context interface to obtain the sensormanager instance:

Sensormanager manager = (sensormanager) Context. getsystemservice (context. sensor_service );

Sensormanager is a system service provided by the Android system. Android has multiple system services, and each service can provide us with different system information.

Once you obtain the sensormanager instance, you can check whether the accelerator is available:

Boolean hasaccel = manager. getsensorlist (sensor. type_accelerometer). Size ()> 0;

Through this code, we query the manager to learn about all installed accelerometer types. This means that a device can have multiple accelerometer. However, only one Accelerometer Sensor is actually returned.

If you have installed an accelerator, you can use sensormanager to obtain it and register the sensoreventlistener, as shown below:

Sensor sensor = manager. getsensorlist (sensor. type_accelerometer). Get (0 );

Boolean sucess = manager. registerlistener (listener, sensor, sensormanager. sensor_delay_game );

The sensormanager. sensor_delay_game parameter is used to specify the update frequency of the listener. The update content comes from the latest status of the accelerator.

The sensormanager. registerlistener () method returns a Boolean variable to indicate whether the registration process is successful. To ensure any sensor event, we need to spread the Boolean variable.

Once the listener is successfully registered, we can use the sensoreventlistener. onsensorchanged () method to receive the sensorevent. This method is called only when the sensor status changes.

Now it is time to process sensorevent. This sensorevent has a public floating point array member variable sensorevent. values, which stores the acceleration values of the current three axes of the accelerator. Sensorevent. Values [0] saves the value of the X axis, sensorevent. Values [1] saves the value of the Y axis, and sensorevent. Values [2] saves the value of the Z axis.

In general, the X and Y axes are in the plane where your mobile phone screen is located, while the Z axis is perpendicular to the plane where the mobile phone screen is located. The X axis is generally in the direction of the short side of the mobile phone,

Other coordinate axes can give full play to your space imagination.

The Code is as follows:

package org.example.ch04_android_basics;import android.app.Activity;import android.content.Context;import android.hardware.Sensor;import android.hardware.SensorEvent;import android.hardware.SensorEventListener;import android.hardware.SensorManager;import android.os.Bundle;import android.widget.TextView;public class AccelerometerTest extends Activity implements SensorEventListener{TextView textView;StringBuilder builder = new StringBuilder();@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);textView = new TextView(this);setContentView(textView);SensorManager manager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);if(manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() == 0){textView.setText("No accelerometer installed");}else{Sensor accelerometer = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);if(!manager.registerListener(this, accelerometer,SensorManager.SENSOR_DELAY_GAME)){textView.setText("Couldn't register sensor listener");}}}@Overridepublic void onAccuracyChanged(Sensor sensor, int accuracy) {// TODO Auto-generated method stub}@Overridepublic void onSensorChanged(SensorEvent event) {// TODO Auto-generated method stubbuilder.setLength(0);builder.append("x: ");builder.append(event.values[0]);builder.append(", y: ");builder.append(event.values[1]);builder.append(", z: ");builder.append(event.values[2]);textView.setText(builder.toString());}}

Running Effect (my mobile phone is flat on the desktop, so the acceleration in the X and Y directions is almost 0, and the Z axis is about 9.8 of the gravity acceleration ):


Now let's take a look at how a mobile phone knows its pitch angle, turning angle, and direction like an airplane. The method is similar to getting the accelerator information, that is, it gets different sensor types. Here we are:

Sensor compass = manager. getdefasensensor (sensor. type_orientation );

The rest are similar. The Code is as follows:

package org.example.ch04_android_basics;import android.app.Activity;import android.content.Context;import android.hardware.Sensor;import android.hardware.SensorEvent;import android.hardware.SensorEventListener;import android.hardware.SensorManager;import android.os.Bundle;import android.widget.TextView;public class OrientationTest extends Activity implements SensorEventListener{TextView textView;StringBuilder builder = new StringBuilder();float yaw;float pitch;float roll;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);textView = new TextView(this);setContentView(textView);SensorManager manager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);if(manager.getSensorList(Sensor.TYPE_ORIENTATION).size() == 0){textView.setText("No orientation installed");}else{Sensor compass = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);if(!manager.registerListener(this, compass,SensorManager.SENSOR_DELAY_GAME)){textView.setText("Couldn't register sensor listener");}}}@Overridepublic void onAccuracyChanged(Sensor sensor, int accuracy) {// TODO Auto-generated method stub}@Overridepublic void onSensorChanged(SensorEvent event) {// TODO Auto-generated method stubyaw = event.values[0];pitch = event.values[1];roll = event.values[2];calculateOrientation(); }public void calculateOrientation(){builder.setLength(0);builder.append("yaw: ");builder.append(yaw + "\n");builder.append("pitch: " );builder.append(pitch + "\n");builder.append("roll: ");builder.append(roll);textView.setText(builder.toString());}}

The yaw stores the yaw angle, that is, the deviation angle from the direction of the Earth's magnetic field. The range is between [0,360] degrees.

Pitch stores the pitch angle of the mobile phone. The range is between [-180,180] degrees.

Roll stores the Rotation Angle of the mobile phone. The range is between [-90, 90] degrees.

Now I have my cell phone flat on the desktop and direct it to the East. How much will it show? The running effect is as follows:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.