Android game development 18: use sensors to develop games! (This article explains how to use a gravity sensor to control the movement of the sphere in surfaceview)

Source: Internet
Author: User
Tags drawtext

Li huaming himiOriginal, reprinted must be explicitly noted:
Reprinted from[Heimi gamedev block]Link: http://www.himigame.com/android-game/344.html

 

Many kids shoes say that after my code is run, clicking home or back will cause a program exception. If you have encountered this, you certainly haven't carefully read the himi blog, in article 19th, himi specifically wrote about the causes and solutions of these errors. I have added my remarks on this blog, and my provincial children's shoes are always confused. Please click here to contact us for further reading:

[Android game development 19th] (required) surfaceview Running Mechanism explanation-analyze back and home buttons and switch to the background to handle exceptions!

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 and frequently used sensor in game development,Acceleration Sensor (gravity sensor )!


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


 

/** <Br/> * @ author himi <br/> * @ sensor accelerometer, also known as gravity Sensor <br/> * @ SDK 1.5 (API 3) the sensor is supported <br/> * @ explanation: This sensor not only detects the player's mobile phone reversal action, but also determines the extent to which the mobile phone is reversed, the value of the sensor is different! <Br/> */<br/> public class mysurfaceview extends surfaceview implements callback, runnable {<br/> private thread th = new thread (this ); <br/> private surfaceholder SFH; <br/> private canvas; <br/> private paint; <br/> private sensormanager Sm; <br/> private sensor; <br/> private sensoreventlistener mysensorlistener; <br/> private int arc_x, arc_y; // position of x and y in the circle <br/> private float x = 0, Y = 0, Z = 0; <br/> Public mysurfaceview (context) {<br/> super (context); <br/> This. setkeepscreenon (true); <br/> SFH = This. getholder (); <br/> SFH. addcallback (this); <br/> paint = new paint (); <br/> paint. setantialias (true); <br/> setfocusable (true); <br/> setfocusableintouchmode (true ); <br/> // obtain the sensor management object through the service <br/> Sm = (sensormanager) mainactivity. ma. getsystemservice (service. sensor_service); <br/> Se Nsor = Sm. getdefasensensor (sensor. type_accelerometer); // obtain a gravity sensor instance <br/> // type_accelerometer (gravity sensor) type. <Br/> // type_all describes all types of sensors. <Br/> // type_gyroscope gyroscope sensor type <br/> // type_light optical sensor type <br/> // type_magnetic_field constant magnetic field sensor type. <Br/> // type of the type_orientation direction sensor. <Br/> // type_pressure describes a constant pressure sensor type <br/> // type_proximity constant description type proximity sensor <br/> // type_temperature temperature sensor type description <br/> mysensorlistener = new sensoreventlistener () {<br/> @ override <br/> // response to this function when the value obtained by the sensor changes <br/> Public void onsensorchanged (sensorevent event) {// Note 1 <br/> // the value obtained by the sensor changes. Handle the changes here <br/> X = event. values [0]; // tumble horizontally on the mobile phone <br/> // x> 0 indicates turning left on the current mobile phone x <0 turns right over <br/> Y = event. values [1]; // scroll down the phone vertically <br/> // y> 0 indicates that the current phone is flipped down Y <0 flip up <B R/> Z = event. values [2]; // screen orientation <br/> // z> 0 mobile phone screen upwards z <0 mobile phone screen downwards <br/> arc_x-= X; // Note 2 <br/> arc_y + = y; <br/>}< br/> @ override <br/> // response to this function when the sensor's precision changes <br/> Public void onaccuracychanged (sensor, int accuracy) {<br/> // todo auto-generated method stub <br/>}< br/>}; <br/> SM. registerlistener (mysensorlistener, sensor, sensormanager. sensor_delay_game); <br/> // The first parameter is the sensor listener, and the second parameter is the sensor instance to be monitored <br/> // The last parameter. Is the sensor speed type of the listener: A total of four forms <br/> // sensor_delay_normal normal <br/> // sensor_delay_ui suitable for games <br/> // sensor_delay_game ~) <Br/> // sensor_delay_fastest fastest <br/>}< br/> Public void surfacecreated (surfaceholder holder) {<br/> arc_x = This. getwidth ()/2-25; <br/> arc_y = This. getheight ()/2-25; <br/> th. start (); <br/>}< br/> Public void draw () {<br/> try {<br/> canvas = SFH. lockcanvas (); <br/> If (canvas! = NULL) {<br/> canvas. drawcolor (color. black); <br/> paint. setcolor (color. red); <br/> canvas. drawarc (New rectf (arc_x, arc_y, arc_x + 50, <br/> arc_y + 50), 0,360, true, paint); <br/> paint. setcolor (color. yellow); <br/> canvas. drawtext ("Current gravity sensor value:", arc_x-50, arc_y-30, paint); <br/> canvas. drawtext ("x =" + x + ", y =" + Y + ", Z =" + Z, <br/> arc_x-50, arc_y, paint ); <br/> string temp_str = "himi prompt:"; <br/> String temp_str2 = ""; <br/> string temp_str3 = ""; <br/> If (x <1 & x>-1 & Y <1 & Y>-1) {<br/> temp_str + = "the current mobile phone is placed horizontally"; <br/> If (z> 0) {<br/> temp_str2 + = "and screen up"; <br/>} else {<br/> temp_str2 + = "and the screen is down, prompting you not to lie down and play with your phone, poor for your eyes ~ "; <Br/>}< br/>}else {<br/> If (x> 1) {<br/> temp_str2 + = "the current mobile phone is turning left"; <br/>} else if (x <-1) {<br/> temp_str2 + = "the current mobile phone is in the right turn state"; <br/>}< br/> If (Y> 1) {<br/> temp_str2 + = "the current mobile phone is turning down"; <br/>} else if (Y <-1) {<br/> temp_str2 + = "the current mobile phone is turning up"; <br/>}< br/> If (z> 0) {<br/> temp_str3 + = "and screen up"; <br/>} else {<br/> temp_str3 + = "and the screen is down, prompting you not to lie down and play with your phone, poor for your eyes ~ "; <Br/>}< br/> paint. settextsize (20); <br/> canvas. drawtext (temp_str, 0, 50, paint); <br/> canvas. drawtext (temp_str2, 0, 80, paint); <br/> canvas. drawtext (temp_str3, 0,110, paint); <br/>}< br/>} catch (exception e) {<br/> log. V ("himi", "Draw is error! "); <Br/>}finally {<br/> SFH. unlockcanvasandpost (canvas); <br/>}< br/> @ override <br/> Public void run () {<br/> // todo auto-generated method stub <br/> while (true) {<br/> draw (); <br/> try {<br/> thread. sleep (100); <br/>} catch (exception ex) {<br/>}< br/> Public void surfacechanged (surfaceholder holder, int format, int width, int height) {<br/>}< br/> Public void surfacedestroyed (surfaceholder holder) {<br/>}< br/>} 

 

 

 

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.himigame.com/android-game/344.html

 

 


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.