Application of Android gravity sensor in game development _android

Source: Internet
Author: User
Tags drawtext stub

Gesture operation can be said to be a smart phone charm, the first two sections to explain the two interesting gestures, put them in the game, greatly enhance the game's playful and interesting. This section will continue to introduce another magical thing about smartphones: sensors.

first, what is the sensor

The so-called sensor is to be able to detect such as light, heat, temperature, gravity, direction and so on devices.

Ii. What are the sensors that Android offers

1. Acceleration sensor (gravity sensor)

2. Gyro Sensor

3. Optical sensor

4. Constant magnetic field sensor

5. Directional sensor

6. Constant pressure Transducer

7. Proximity Sensor

8. Temperature sensor

Today we introduce the most common game development, the use of the highest frequency of a sensor-accelerometer (gravity sensor)!

Three, the sensor example explains

Because the simulator can not test, so I use the phone to debug, first two screenshots:

The following code is attached:

Java code

The/** * @author Himi * @Sensor Accelerometer, also known as the gravity sensor * @SDK 1.5 (API 3), supports the sensor *@ explanation: This sensor can detect not only the movement of the player's reverse phone, but also the extent to which the mobile phone is being reversed. 
 The value will also be different! * * public class Mysurfaceview extends Surfaceview implements Callback, Runnable {private thread th = new Thread (this  
  );  
  Private Surfaceholder SFH;  
  Private Canvas Canvas;  
  Private Paint Paint;  
  Private Sensormanager SM;  
  Private Sensor Sensor;  
  Private Sensoreventlistener Mysensorlistener;  
  private int arc_x, arc_y;//rounded x,y position private float x = 0, y = 0, z = 0;  
    Public Mysurfaceview {Super (context);  
    This.setkeepscreenon (TRUE);  
    SFH = This.getholder ();  
    Sfh.addcallback (this);  
    Paint = new paint ();  
    Paint.setantialias (TRUE);  
    Setfocusable (TRUE);  
    Setfocusableintouchmode (TRUE);  
    The Sensor management Object SM = (Sensormanager) MainActivity.ma.getSystemService (Service.sensor_service) is obtained through the service; Sensor = Sm.getdefaultsensor (sensor.type_accelerometer);//Get a gravity sensor instance//tYpe_accelerometer acceleration Sensor (gravity sensor) type.  
    Type_all describes all types of sensors.  
    Type_gyroscope Gyroscope sensor type//type_light light sensor type//type_magnetic_field constant magnetic field sensor type.  
    Type_orientation direction sensor type. Type_pressure describes a constant pressure sensor type//type_proximity constant description type Proximity sensor//type_temperature temperature sensor type description Mysenso Rlistener = new Sensoreventlistener () {@Override///sensor Gets the value changed in response to this function public void onsensorchanged (S Ensorevent event) {//Memo 1//The sensor gets the value to change, this processing x = event.values[0];//mobile phone horizontal tumbling//x>0 The current cell phone left turn x <0 Right Turn y = event.values[1]; Mobile phone vertical Tumbling//y>0 shows that the current mobile phone under the turn y<0 z = event.values[2];  
      The screen faces the//z>0 phone screen facing up z<0 mobile screen arc_x-= x;//Note 2 arc_y = y;  
        The response to this function is public void onaccuracychanged (Sensor Sensor, int accuracy) {When the accuracy of the @Override//sensor changes.  
    TODO auto-generated Method stub}}; Sm.registErlistener (Mysensorlistener, sensor, sensormanager.sensor_delay_game); The first parameter is the sensor listener, the second is the sensing instance that needs to be monitored//the last parameter is the type of sensor rate to monitor: altogether four forms//sensor_delay_normal normal//sensor_delay_ui suitable Interface//sensor_delay_game for games (we must choose this wow haha ~)//sensor_delay_fastest the fastest} public void surfacecreated (Sur  
    Faceholder holder) {arc_x = This.getwidth ()/2-25;  
    Arc_y = This.getheight ()/2-25;  
  Th.start ();  
      public void Draw () {try {canvas = Sfh.lockcanvas ();  
        if (canvas!= null) {Canvas.drawcolor (color.black);  
        Paint.setcolor (color.red);  
        Canvas.drawarc (New RECTF (arc_x, arc_y, arc_x +, arc_y +), 0, 360, true, paint);  
        Paint.setcolor (Color.yellow);  
        Canvas.drawtext ("Current Gravity Sensor value:", arc_x-50, arc_y-30, paint);  
        Canvas.drawtext ("x=" + x + ", y=" + y + ", z=" + Z, arc_x-50, arc_y, paint);  
        String temp_str = "Himi hint:"; StRing TEMP_STR2 = "";  
        String TEMP_STR3 = "";  
          if (x < 1 && x >-1 && y < 1 && y >-1) {temp_str + = "Current mobile phone is placed horizontally";  
          if (Z > 0) {temp_str2 + = "and screen facing up";  
          else {temp_str2 = "and the screen facing down, prompted not to play on the phone, bad for the eyes ~";  
          } else {if (x > 1) {temp_str2 + = "The current phone is in the left-turn state";  
          else if (x <-1) {TEMP_STR2 + = "The current phone is in the right turn of the state";  
          } if (Y > 1) {temp_str2 + = "The current phone is in the downward-turning state";  
          else if (Y <-1) {temp_str2 + = "Current mobile phone is upside down";  
          } if (Z > 0) {temp_str3 + = "and screen facing up";  
          else {TEMP_STR3 = "and the screen facing down, prompted not to play on the phone, bad for the eyes ~";  
        } paint.settextsize (20);  
        Canvas.drawtext (temp_str, 0, paint);  
        Canvas.drawtext (temp_str2, 0, paint); CanvAs.drawtext (TEMP_STR3, 0, paint);  
    The catch (Exception e) {log.v ("Himi", "Draw is error!");  
    finally {sfh.unlockcanvasandpost (canvas);   
      @Override public void Run () {//TODO auto-generated method stub while (true) {draw ();  
      try {thread.sleep (100); ' Catch (Exception ex) {}} ' public void surfacechanged (surfaceholder holder, int format, int Widt   h, int height) {} public void surfacedestroyed (Surfaceholder holder) {}

Note 1:

The Sensoreventlistener onsensorchanged event returns the Sensorevent object, containing the latest data for sensor, and obtains a event.values by float[] Array! For different sensor types, The array contains a different number of elements, and the gravity sensor always returns an array of length 3 representing the values in the X, y, and z directions respectively. The z-axis indicates whether the cell phone is on the screen or the screen is facing down.

Here also pay attention to your current mobile phone in portrait or landscape, because this will affect the meaning of our x,y expression!

If the current phone is a portrait screen:

X>0 description of the current mobile phone left turn x<0 right turn;

Y>0 explain the current mobile phone down y<0 turn over.

If the current phone is a landscape screen:

X>0 description of the current mobile phone x<0 turn over;

Y>0 description of the current mobile phone right turn y<0 left turn.

I would like to remind you that children's shoes:

1, to consider the player is currently holding mobile phone posture, such as vertical screen, horizontal screen.

2, according to the different screen, although the screen coordinate system will automatically change, but the value of the sensor will not automatically change the coordinate system! So why does the horizontal screen vertical screen change when we take out the value of the sensor to indicate that the action is not the same reason! Therefore, when the game development for people moving, picture moving and so on, when the operation, gesture x,y positive negative mean what must think clearly! Otherwise the player will play with vomit (too faint!). )- -、

NOTE 2:

This should have been arc_x+=x, but because my screen is now portrait! Cause x>0 gesture means that the player will turn the phone left, but the circle of our screen should be based on the reversal of the corresponding move, then the player will turn the phone left, we should let the prototype's x-coordinate reduction! So here is written the arc_x-=x;

Summary

Although this section only speaks of gravity sensors, this is enough, because if you want to use a different sensor, just follow these steps:

1. Use Sensormanager.getdefaultsensor (); Pass in a parameter of the sensor you want to get its example;

2, registration;

3, in the listener to handle the event.

It is not difficult, you can also let your game have a variety of induction effect.

       above on the Android Gravity sensor data collation, follow-up continue to supplement the relevant knowledge, thank you for your support for this site!

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.