Android Physics game's Gravity System development sample Code _android

Source: Internet
Author: User

This section provides you with a knowledge of the physics game and explains the writing of a simple round free fall demo. The gravity system to be introduced in this paper is actually similar.

In a gravity sensor, although I also realized that a circle has different speeds depending on the angle of the phone's reversal, its built-in acceleration algorithms are all encapsulated by the Android OS, and today we're going to talk about a gravity system that simulates this acceleration, allowing a free falling circle, The feeling is as good as the actual ball of quality! When the whereabouts of the speed is accelerated, rebound after the speed slowly reduced.

First paste two screenshots of the effect, so that everyone has an intuitive understanding, and then detailed explanation:

Introduction to Round Free Fall Demo

When you click on the Simulator any button will randomly generate a random size on the screen, random color, random position, flashing a circle, and the circle has gravity, in the free fall, when the circle touches the bottom of the screen will bounce, and the height of the rebound is lower than once! (hehe, playing a bit of h, crazy dot button to do full screen are-)

In this example, in order to look good, I did not let the circle finally slow to stop, will always be in a height of rebound, whereabouts.

One more thing: for a circle to fall free from a height, it may not change in the X coordinate system, of course this is in our code, belong to the ideal state, because in real life, general x/y coordinate system will have changes, in this demo, I mainly vertical drop and rebound function to make, About the level of acceleration I did not do, the first is because and vertical treatment of the basic line of thought, the 2nd I have no time ~ ~

Okay, no nonsense! Let me introduce my custom circle class:

Java code

Package Com.himi;  
Import Java.util.Random;  
Import Android.graphics.Canvas;  
Import Android.graphics.Color;  
Import Android.graphics.Paint;  
Import Android.graphics.RectF; /** * @author Himi * @ Custom Circle class/public class Myarc {private int arc_x, arc_y, arc_r;//round x,y coordinates and RADIUS private float speed_x = 1.2f, speed_y = speed of x and y of 1.2f;//ball private float vertical_speed;//acceleration private float horizontal_speed   
  //horizontal acceleration, everyone try to add it. Private final float ACC = 0.135f;//in order to simulate the offset value of the acceleration private final float recession = 0.2f;//coefficient of decay per bounce  
   Private Boolean Isdown = true;//is in a falling state private Random ran;//the random library/** * @ defines a circular constructor * @param x round x coordinates  
    * @param y circular y coordinate * @param r circular Radius/public Myarc (int x, int y, int r) {ran = new Random ();  
    this.arc_x = x;  
    this.arc_y = y;  
  This.arc_r = R; public void Drawmyarc (Canvas Canvas, Paint Paint) {//each circle should have a painting method Paint.setcolor (Getrandomcolor ()); constant access  
 That is, the color, fill the circle (to achieve a circular blinking effect)   Canvas.drawarc (New RECTF (arc_x + speed_x, arc_y + speed_y, arc_x + 2 * arc_r + speed_x, arc_y + 2 * arc_r + s)  
  Peed_y), 0, 360, true, paint);  
    /** * @return * @ Returns a color/public int getrandomcolor () {int ran_color = Ran.nextint (8);  
    int temp_color = 0;  
      Switch (ran_color) {case 0:temp_color = Color.White;  
    Break  
      Case 1:temp_color = Color.Blue;  
    Break  
      Case 2:temp_color = Color.cyan;  
    Break  
      Case 3:temp_color = Color.dkgray;  
    Break  
      Case 4:temp_color = color.red;  
    Break  
    Case 6:temp_color = Color.green;  
    Case 7:temp_color = Color.gray;  
      Case 8:temp_color = Color.yellow;  
    Break  
  return temp_color; /** * Circular logic/public void logic () {//each circle should have a set of logical if (Isdown) {//Circular drop logic/*--remarks 1-*/speed_y + ve rtical_speed;//Circular y-axis speed plus acceleration int COUNT = (int) vertical_speed++;  Here, take another variable. Note The current speed offset//If the following for (int i = 0; i < vertical_speed++ i++) {} Then the loop is dead-for (int i = 0; i < count;  
      i++) {//Memo 1/*--Note 2-*/vertical_speed + = ACC;  
      } else {//circular bounce logic speed_y-= vertical_speed;  
      int count = (int) vertical_speed--;  
      for (int i = 0; i < count; i++) {vertical_speed-= ACC;  
      } if (Iscollision ()) {Isdown =!isdown;//when a collision indicates that the direction of the circle is going to change! Vertical_speed-= Vertical_speed * recession;//Each collision will decay the bounce acceleration}/** * Circular collision with the bottom of the screen * @return *   
  Returns True Collision/public Boolean iscollision () {return arc_y + 2 * arc_r + speed_y >= mysurfaceviee.screenh;  }  
}

Relatively simple mainly explain the next few notes:

Note 1:

It is estimated that some students see a little dizzy here, I explained, we all know that when the free fall, the speed is getting faster, this is affected by the acceleration, so here we have the original circular Y speed on the basis of plus acceleration!

Some children's shoes here say for the loop can be abbreviated, then I will prompt everyone:

 for (int i = 0; i < count; i++) {

        vertical_speed + = ACC;

    }

The above code can actually be expressed in one sentence:

Vertical_speed +=acc*count; or vertical_speed =vertical_speed + acc*count;

But note: Because I am here the variables are floating-point numbers, we all know that for floating-point numbers have a bit limit, then I use for to write can avoid the product, if the shorthand form will have a difference in the resulting results! So be careful.

Also must not be abbreviated into vertical_speed = (vertical_speed +acc) *count; This is wrong!

NOTE 2:

Although the acceleration affects the original speed of the circle, but our acceleration is not constant, in order to simulate the free whereabouts of the real sphere, here we not only increase the speed of the offset ACC, and we have to change the law of its simulation, so that the next acceleration offset exponentially increase! So why take the value of the accelerator as a criterion for the for loop when you want the FOR loop!

OK, here's a look at our surfaceview.

Package Com.himi;  
Import Java.util.Random;  
Import Java.util.Vector;  
Import Android.content.Context;  
Import Android.graphics.Canvas;  
Import Android.graphics.Color;  
Import Android.graphics.Paint;  
Import Android.util.Log;  
Import android.view.KeyEvent;  
Import Android.view.SurfaceHolder;  
Import Android.view.SurfaceView;  
Import Android.view.SurfaceHolder.Callback;  
  public class Mysurfaceviee extends Surfaceview implements Callback, Runnable {private Thread th;  
  Private Surfaceholder SFH;  
  Private Canvas Canvas;  
  Private Paint Paint;  
  Private Boolean flag;  
  public static int Screenw, SCREENH;  
    Private Vector<myarc> vc;//Here define our custom round container private Random ran;//the library public Mysurfaceviee  
    Super (context);  
    This.setkeepscreenon (TRUE);  
    VC = new vector<myarc> ();  
    ran = new Random ()//memo 1 SFH = This.getholder ();  
    Sfh.addcallback (this);  
    Paint = new paint (); Paint.setantialias (tRue);  
  Setfocusable (TRUE);  
    } public void surfacecreated (Surfaceholder holder) {flag = true;//This is the last one I just talked about ...  
    th = new Thread (this);  
    Screenw = This.getwidth ();  
    Screenh = This.getheight ();  
  Th.start ();  
      public void Draw () {try {canvas = Sfh.lockcanvas ();  
      Canvas.drawcolor (Color.Black); if (VC!= null) {///when the container is not empty, iterate through all the circle-drawing methods in the container for (int i = 0; i < vc.size (); i++) {Vc.elementat (i). Draw  
        Myarc (canvas, paint); Exception e) {//Todo:handle Exception} finally {try {if (  
      Canvas!= null) sfh.unlockcanvasandpost (canvas); Exception E2 {}}} private void logic () {//main logic if (VC!= null) {///when container is not empty, traverse all circles in container  
      logic for (int i = 0; i < vc.size (); i++) {vc.elementat (i); logic (); @Override public boolean onKeyDown (int keycode,KeyEvent event) {//When the keystroke event responds, we still have our circular instance vc.addelement to the container (new Myarc (Ran.nextint (This.getwidth ()), Ran.nextint (  
    ), Ran.nextint (50));  
  return true;  
      public void Run () {//TODO auto-generated method stub while (flag) {logic ();  
      Draw ();  
      try {thread.sleep (100); ' Catch (Exception ex) {}} ' public void surfacechanged (surfaceholder holder, int format, int Widt  
  h, int height) {log.v ("Himi", "surfacechanged");  
  public void surfacedestroyed (Surfaceholder holder) {flag = false;   }

OK, the code is very simple, also very clear! A little bit: like the myarc inside there are similar mysurfaceview in the same way logic () and draw (), so that better manage our code structure, clear thinking, each to do their duty to avoid confusion.

The above is the Android development of gravity system data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!

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.