Android Mini-game templates-gravity sensor

Source: Internet
Author: User
Tags drawtext android games

Long time no Update blog, today to talk about Android games ——— gravity induction, generally used in the game more, such as this kind of game has: Temple escape, need for speed, balance ball, measurements gravity maze, gravity racing and so on.

First what is gravity sensing, which is a device commonly used in mobile phones, and an accelerometer. When the phone is stationary, acceleration is gravity, so it is also called a gravity sensor. This hardware can sense the change of acceleration and transform it into the data provided to the system. Another sensor is a gyroscope that detects rotational movements around an axis, using a mass of rigid bodies to rotate or vibrate, if the rotation is perpendicular to the rotation or vibration axis, because inertia produces a force perpendicular to the rotation or vibration axis (G-sensor is the acceleration force). The gyroscope must be divided into X, Y and Z axes. The difference is the former, the internal measurement object is the acceleration force, the latter, the internal measurement of the Coriolis force. The former tells you that the object is not moving, which direction is moving? Does the latter tell you that the moving object is turning? How many degrees did it turn? Multi-axis g-sensor can also detect the rotation of the object tangent to the vertical direction, but the angle is difficult to judge.

So what is the principle of cell phone gravity sensor? Following

--through the force-sensitive sensor, feel the mobile phone in the changing posture, the change of center of gravity, so that the mobile phone cursor changes position to achieve the function of choice.   Mobile Gravity sensor technology: the use of piezoelectric effect, in short, is to measure the interior of a heavy weight (weight and piezoelectric film into one) gravity orthogonal two-direction of the size of the force, to determine the horizontal direction. Mobile phone gravity sensor refers to the mobile phone built-in gravity stick chip, support for shaking switch the required interface and functions, shake the screen, flip mute, swing switch video, etc., is a very fun to use the function.

Here's a simple little Game (example):apk:http://download.csdn.net/detail/liuyang1990i/7448211





The code is as follows: (part Java code below)

Startactivity.java file

Package Cn.m15.xys;


Import android.app.Activity;
Import Android.content.Context;
Import android.content.Intent;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;


public class StartActivity extends Activity {
Context mcontext = null;
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Mcontext = this;

/** into the game world-small ball mobile **/
Button Botton0 = (button) Findviewbyid (R.id.button0);
Botton0.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View arg0) {
Intent Intent = new Intent (mcontext,surfaceviewacitvity.class);
StartActivity (Intent);
}
});

}
}



Surfaceviewacitvity.java file

Package Cn.m15.xys;




Import android.app.Activity;
Import Android.content.Context;
Import Android.content.pm.ActivityInfo;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.graphics.Canvas;
Import Android.graphics.Color;
Import Android.graphics.Paint;
Import Android.hardware.Sensor;
Import android.hardware.SensorEvent;
Import Android.hardware.SensorEventListener;
Import Android.hardware.SensorManager;
Import Android.os.Bundle;
Import Android.view.SurfaceHolder;
Import Android.view.SurfaceView;
Import Android.view.Window;
Import Android.view.WindowManager;
Import Android.view.SurfaceHolder.Callback;




public class Surfaceviewacitvity extends Activity {


MyView Manimview = null;


@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Full Screen display window
Requestwindowfeature (Window.feature_no_title);
GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
Force horizontal Screen
Setrequestedorientation (Activityinfo.screen_orientation_landscape);

Display a custom game view
Manimview = new MyView (this);
Setcontentview (Manimview);
}


public class MyView extends Surfaceview implements Callback,runnable, sensoreventlistener{


/** Refresh the screen every 50 frames **/
public static final int time_in_frame = 30;


/** Game Brush **/
Paint mpaint = null;
Paint mtextpaint = null;
Surfaceholder msurfaceholder = null;


/** Control game Update Cycle **/
Boolean mrunning = false;


/** Game Canvas **/
Canvas Mcanvas = null;


/** Control Game Loop **/
Boolean misrunning = false;

/**sensormanager Manager **/
Private Sensormanager msensormgr = null;
Sensor msensor = null;

/** mobile phone screen width high **/
int mscreenwidth = 0;
int mscreenheight = 0;

/** Ball resource file out-of-bounds area **/
private int mscreenballwidth = 0;
private int mscreenballheight = 0;

/** Game Background File **/
Private Bitmap MBITMAPBG;

/** Pellet resource File **/
Private Bitmap Mbitmapball;

Coordinate position of/** ball **/
Private float MPOSX = 200;
private float mposy = 0;

/** Gravity-sensing X-axis y-axis z-axis gravity value **/
private float MGX = 0;
private float MGY = 0;
private float MGZ = 0;

Public MyView (Context context) {
Super (context);
/** Setting the current view has control focus **/
This.setfocusable (TRUE);
/** set the current view to have touch events **/
This.setfocusableintouchmode (TRUE);
/** Get Surfaceholder Object **/
Msurfaceholder = This.getholder ();
/** add Msurfaceholder to the callback callback function **/
Msurfaceholder.addcallback (this);
/** Creating a canvas **/
Mcanvas = new Canvas ();
/** creating a curve brush **/
Mpaint = new Paint ();
Mpaint.setcolor (Color.White);
/** Loading Pellet Resources **/
Mbitmapball = Bitmapfactory.decoderesource (This.getresources (), r.drawable.ball);
/** Loading Game Background **/
MBITMAPBG = Bitmapfactory.decoderesource (This.getresources (), r.drawable.bg);

/** Get Sens
* Ormanager Object **/
Msensormgr = (Sensormanager) getsystemservice (Sensor_service);
Msensor = Msensormgr.getdefaultsensor (Sensor.type_accelerometer);
Register Listener, the third parameter is the accuracy of the detection
Sensor_delay_fastest is the most sensitive, because it's too fast, no need to use
Use of Sensor_delay_game game development
Sensor_delay_normal Normal speed
sensor_delay_uiThe slowest speed
Msensormgr.registerlistener (This, msensor, sensormanager.sensor_delay_game);
}

private void Draw () {

/** Drawing Game Background **/
Mcanvas.drawbitmap (mbitmapbg,0,0, mpaint);
/** Draw Small Ball **/
Mcanvas.drawbitmap (Mbitmapball, Mposx,mposy, Mpaint);
/**x Axis y axis Z-axis gravity value **/
Mcanvas.drawtext ("x-axis Gravity value:" + MGX, 0, Mpaint);
Mcanvas.drawtext ("y-axis Gravity value:" + MGY, 0, +, mpaint);
Mcanvas.drawtext ("z-axis Gravity value:" + MGZ, 0, X, mpaint);
}

@Override
public void surfacechanged (surfaceholder holder, int format, int width,
int height) {


}


@Override
public void surfacecreated (Surfaceholder holder) {
/** start Game main loop thread **/
Misrunning = true;
New Thread (This). Start ();
/** get current screen width high **/
Mscreenwidth = This.getwidth ();
Mscreenheight = This.getheight ();

/** Get ball Cross area **/
Mscreenballwidth = Mscreenwidth-mbitmapball.getwidth ();
Mscreenballheight = Mscreenheight-mbitmapball.getheight ();
}


@Override
public void surfacedestroyed (Surfaceholder holder) {
Misrunning = false;
}


@Override
public void Run () {
while (misrunning) {


/** time to get the game updated before **/
Long startTime = System.currenttimemillis ();


/** here Add line Shuo full lock **/
Synchronized (Msurfaceholder) {
/** get the current canvas and lock **/
Mcanvas = Msurfaceholder.lockcanvas ();
Draw ();
/** After drawing finishes unlocking the display on the screen **/
Msurfaceholder.unlockcanvasandpost (Mcanvas);
}


/** get updated game end time **/
Long endTime = System.currenttimemillis ();


/** calculates the number of milliseconds the game is updated in a single **/
int difftime = (int) (endtime-starttime);


/** ensure that each update time is 50 frames **/
while (Difftime <= time_in_frame) {
Difftime = (int) (System.currenttimemillis ()-startTime);
/** thread waits for **/
Thread.yield ();
}


}


}

@Override
public void onaccuracychanged (Sensor arg0, int arg1) {
TODO auto-generated Method Stub

}


@Override
public void Onsensorchanged (Sensorevent event) {
MGX = event.values[sensormanager.data_x];
Mgy= event.values[sensormanager.data_y];
MGZ = Event.values[sensormanager.data_z];


This is multiplied by 2 to make the ball move faster.
MPOSX-= MGX * 2;
Mposy + = MGY * 2;


Detects if the ball is out of bounds
if (Mposx < 0) {
MPOSX = 0;
} else if (Mposx > Mscreenballwidth) {
Mposx = Mscreenballwidth;
}
if (Mposy < 0) {
Mposy = 0;
} else if (Mposy > Mscreenballheight) {
Mposy = Mscreenballheight;
}
}
}
}



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.