Android game development 18: use sensors to develop games!

Source: Internet
Author: User
Tags drawtext

 

The first two articles introduced two very interesting gesture operations. embedded in our game, we have to say that it adds a lot of flexibility, playability, and fun to the game! We will continue to introduce you to the highlights today! Sensor!

 

I. What is a sensor:

Sensors can detect functions such as light, heat, temperature, gravity, and direction!

 

Ii. Which sensors are provided in Android:

1. Acceleration Sensor (gravity sensor)

2. gyroscope Sensor

3. Optical Sensors

5. Constant Magnetic Field Sensor

6. Direction Sensor

7. Constant Pressure Sensors

8. Proximity sensor

9. Temperature Sensor

 

Today, we will introduce the most common type of sensor in game development, the most frequently used sensor, and the acceleration sensor (gravity sensor )!

 

Because the simulator cannot be tested, I used my mobile phone to debug it ~, First two;

 


 

 

 

··· · 50 ······· · 90 ····· · 140 · 150

/**

* @ Author Himi

* @ Sensor acceleration Sensor, also known as gravity Sensor

* @ SDK 1.5 (api 3) supports sensors.

* @ Explanation: This sensor not only detects the player's mobile phone reversal action, but also gets different sensor values based on the extent to which the mobile phone is reversed!

*/

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; // The position of x and y in the circle

Private float x = 0, y = 0, z = 0;

Public MySurfaceView (Context context ){

Super (context );

This. setKeepScreenOn (true );

Sfh = this. getHolder ();

Sfh. addCallback (this );

Paint = new Paint ();

Paint. setAntiAlias (true );

SetFocusable (true );

SetFocusableInTouchMode (true );

// Get the sensor management object through the service

Sm = (SensorManager) MainActivity. ma. getSystemService (Service. SENSOR_SERVICE );

Sensor = sm. getdefasensensor (Sensor. TYPE_ACCELEROMETER); // obtain a gravity sensor instance.

// Type of the TYPE_ACCELEROMETER accelerometer (gravity sensor.

// TYPE_ALL describes all types of sensors.

// TYPE_GYROSCOPE gyroscope sensor type

// TYPE_LIGHT Optical Sensor Type

// TYPE_MAGNETIC_FIELD constant magnetic field sensor type.

// Type of the sensor in the TYPE_ORIENTATION direction.

// TYPE_PRESSURE describes a constant pressure sensor type

// TYPE_PROXIMITY constant description close sensor

// TYPE_TEMPERATURE temperature sensor type description

MySensorListener = new SensorEventListener (){

@ Override

// Response to this function when the value obtained by the sensor changes

Public void onSensorChanged (SensorEvent event) {// Note 1

// The value obtained by the sensor is changed and processed here

X = event. values [0]; // tumble horizontally on the mobile phone

// X> 0 indicates that the current mobile phone is flipped left x <0 indicates that the mobile phone is flipped right.

Y = event. values [1]; // scroll down the phone vertically

// Y> 0 indicates that the current mobile phone is flipped down. y <0 indicates that the current mobile phone is flipped down.

Z = event. values [2]; // screen orientation

// Z> 0 mobile phone screen up z <0 mobile phone screen down

Arc_x-= x; // Note 2

Arc_y + = y;

}

@ Override

// Response to this function when the sensor's precision changes

Public void onAccuracyChanged (Sensor sensor, int accuracy ){

// TODO Auto-generated method stub

}

};

Sm. registerListener (mySensorListener, sensor, SensorManager. SENSOR_DELAY_GAME );

// The first parameter is the sensor listener, and the second parameter is the sensor instance to be monitored.

// The last parameter is the sensor speed type of the listener. There are four formats in total.

// SENSOR_DELAY_NORMAL

// SENSOR_DELAY_UI

// SENSOR_DELAY_GAME is suitable for games (we must select this option ~)

// SENSOR_DELAY_FASTEST is the fastest

}

Public void surfaceCreated (SurfaceHolder 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 + 50,

Arc_y + 50), 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 prompt :";

String temp_str2 = "";

String temp_str3 = "";

If (x <1 & x>-1 & y <1 & y>-1 ){

Temp_str + = "the current mobile phone is placed horizontally ";

If (z> 0 ){

Temp_str2 + = "and screen up ";

} Else {

Temp_str2 + = "and the screen is down, prompting you not to lie down and play with your phone. It's not good for your eyes ~ ";

}

} Else {

If (x> 1 ){

Temp_str2 + = "the current mobile phone is in the Left flip status ";

} Else if (x <-1 ){

Temp_str2 + = "the current mobile phone is in the right turn state ";

}

If (y> 1 ){

Temp_str2 + = "the current mobile phone is turning down ";

} Else if (y <-1 ){

Temp_str2 + = "the current mobile phone is turning up ";

}

If (z> 0 ){

Temp_str3 + = "and screen up ";

} Else {

Temp_str3 + = "and the screen is down, prompting you not to lie down and play with your phone. It's not good for your eyes ~ ";

}

}

Paint. setTextSize (20 );

Canvas. drawText (temp_str, 0, 50, paint );

Canvas. drawText (temp_str2, 0, 80, paint );

Canvas. drawText (temp_str3, 0,110, paint );

}

} 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 width, int height ){

}

Public void surfaceDestroyed (SurfaceHolder holder ){

}

}

 

 

 

 

Note 1:

The onSensorChanged event of SensorEventListener will return the SensorEvent object, which contains the latest Sensor data, and obtain a float [] array through event. values! For different sensor types, the array contains different numbers of elements. The gravity sensor always returns an array with a length of 3, representing the values in the X, Y, and Z directions, respectively. The Z axis indicates whether the screen is facing up or down;

 

Note that the current mobile phone is still in the vertical or horizontal direction, because this will affect the meaning of X and Y!

If the current mobile phone is a portrait screen:

X> 0 indicates that the current mobile phone is flipped left. x <0 indicates that the mobile phone is flipped right.

Y> 0 indicates that the current mobile phone is flipped down. y <0 indicates that the current mobile phone is flipped down.

If the current mobile phone is a horizontal screen:

X> 0 indicates that the current mobile phone is flipped down x <0

Y> 0 indicates that the current mobile phone is flipped right y <0 Left flip

 

I would like to remind you that:

1. Consider the player's current mobile phone posture, such as portrait screen and landscape screen.

2. Depending on the screen, although the screen coordinate system will automatically change, the sensor value will not automatically change the coordinate system! So why do the values we retrieve from the sensor indicate different actions when the screen is changed !!! Therefore, during game development, when people perform operations such as character movement and image movement, the positive and negative values of gesture X and Y must be clear! Otherwise, the player will play and vomit (too dizzy !) --,

 

NOTE 2:

This should have been arc_x + = x; but because my screen is portrait now! The gesture that causes x> 0 indicates that the player has turned the mobile phone to the left, but the circle on our screen should move according to the reverse of the person. Here, the player turns the mobile phone to the left, we should reduce the X coordinate of the prototype! So here we write arc_x-= x ;!

 

 

To sum up, although this chapter only describes a gravity sensor, it is sufficient because if you want to use another sensor, you only need to perform the following steps:

1. Use SensorManager. getdefasensensor (); input a parameter of the sensor you want to get its instance!

2. register!

3. Process events in the listener!

OK! It's so simple,

 

Source code: http://www.bkjia.com/uploadfile/2011/1115/20111115051806107.rar

 

Himi original, you are welcome to reprint, please note clearly! Thank you.

Address: http://blog.csdn.net/xiaominghimi/archive/2011/01/16/6143520.aspx

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.