This example describes the engine usage of Android game development learning. Share to everyone for your reference. Specifically as follows:
The car engine is the heart of the car, which determines the performance and stability of the car, is a considerable concern when people buy cars. The physical engine in the game, like the engine of a car, occupies a very important position. A good physics engine can simulate the real world very realistically, make the game more realistic, provide a better entertainment experience.
Introduction of JBOX2D
Jbox2d is the Java version of the Open source physics engine box2d, which can be used directly for Android. Because jbox2d Graphics rendering uses the processing library, graphics rendering can only be developed on the Android platform when Jbox2d is used. The engine can automatically simulate the physical motion of 2D rigid body according to the parameters set by the developer, such as gravity, density, friction coefficient and elasticity coefficient.
Second, the example
1. Small ball Bounce Step version
In the 1th section, the drop, collision and bounce of the ball are maintained by code, which is implemented using the physical engine and joins the collision between the Rigidbody.
(1) Constant class constant
Package box2d.bheap;
public class Constant {public
static final float rate=10;//screen with the real world scale public
static final Boolean DRAW_THREAD_FL Ag=true; Draw thread work identity bit public
static final float time_step=2.0f/60.0f//Analog frequency public
static final int itera=10;//Iteration Count public
static int screen_width;//Screen width public
static int screen_height;//Screen height
}
(2) Abstract class Mybody
This class is a custom abstract class and is the base class for all custom Rigidbody classes. Because the rigid body class object in jbox2d only has the function of physical simulation computation, and does not provide the rendering function under the Android platform, the direct use is not very convenient. Therefore, the mybody defines the drawing of a custom rigidbody and the jbox2d physical simulation object.
Package box2d.bheap;
Import Org.jbox2d.dynamics.Body;
Import Android.graphics.Canvas;
Import Android.graphics.Paint;
Public abstract class Mybody {
bodies body;//jbox2d in physical engine int color
;//Rigidbody color public
abstract void Drawsel F (Canvas canvas,paint Paint); method to draw
}
(3) Circular rigid body class Mycirclecolor
Package box2d.bheap;
Import Org.jbox2d.dynamics.Body;
Import Android.graphics.Canvas;
Import Android.graphics.Paint;
Import Android.graphics.Paint.Style;
Import static box2d.bheap.constant.*; Static import public
class Mycirclecolor extends Mybody {
float radius;//circular radius public
Mycirclecolor float Radius,int color) {
this.body=body;
This.radius=radius;
This.color=color;
}
@Override public
void Drawself (Canvas Canvas, Paint Paint) {
paint.setcolor (COLOR&0XCFFFFFF);//Set color
float x=body.getposition (). x*rate;
Float y=body.getposition (). y*rate;
Canvas.drawcircle (x, y, radius, paint); Draw round
Paint.setstyle (style.stroke);//Set hollow no filled
paint.setstrokewidth (1);
Paint.setcolor (color); Draw Side
canvas.drawcircle (x, y, radius, paint);
Paint.reset (); Restore brush Settings
}
}
(4) Rectangular rigid body class Myrectcolor
Package box2d.bheap;
Import static Box2d.bheap.Constant.RATE;
Import Org.jbox2d.dynamics.Body;
Import Android.graphics.Canvas;
Import Android.graphics.Matrix;
Import Android.graphics.Paint; public class Myrectcolor extends Mybody {float halfwidth;//half wide float halfheight;//half high public myrectcolor
, float halfwidth,float halfheight,int color) {this.body=body;
This.halfwidth=halfwidth;
This.halfheight=halfheight;
This.color=color;
public void Drawself (Canvas canvas,paint Paint) {paint.setcolor (COLOR&0X8CFFFFFF);
Float x=body.getposition (). X*rate;
Float y=body.getposition (). Y*rate;
float Angle=body.getangle ();
Canvas.save ();
Matrix m1=new Matrix ();
M1.setrotate ((float) math.todegrees (angle), x, y);
Canvas.setmatrix (M1);
Canvas.drawrect (X-halfwidth, Y-halfheight, X+halfwidth, y+halfheight, paint);
Paint.setstyle (Paint.Style.STROKE);
Paint.setstrokewidth (1);//Set line width Paint.setcolor (color);
Canvas.drawrect (X-halfwidth, Y-halfheight, X+halfwidth, y+halfheight, paint);
Paint.reset ();
Canvas.restore ();
}
}
(5) A tool class that generates a Rigidbody shape box2dutil
Package box2d.bheap;
Import static Box2d.bheap.Constant.RATE;
Import Org.jbox2d.collision.CircleDef;
Import Org.jbox2d.collision.PolygonDef;
Import Org.jbox2d.dynamics.Body;
Import Org.jbox2d.dynamics.BodyDef;
Import Org.jbox2d.dynamics.World; public class Box2dutil {/** * Create rectangular object (color)/public static Myrectcolor Createbox (float x, FL Oat y, float halfwidth, float halfheight, Boolean isstatic,//whether for the rest of the world, int c
Olor) {polygondef shape=new polygondef ();//Create a Polygon Description object if (isstatic) {shape.density=0;
else {shape.density=1.0f; } shape.friction=0.0f; setting friction coefficient shape.restitution=0.6f;
Set Energy loss rate Shape.setasbox (halfwidth/rate, halfheight/rate); Bodydef bodydef=new bodydef (); Create a Rigidbody Description object BodyDef.position.set (x/rate,y/rate); Set position body bodytemp=world.createbody (bodydef); Create a rigid body bodytemp.createshape (shape) in the world; Specify a Rigidbody shape Bodytemp.setmassfroMshapes ();
Set object quality return to new Myrectcolor (Bodytemp, Halfwidth, halfheight, color); /** * Create a Round object (color) */public static Mycirclecolor createcircle (float x, float y, Floa T radius, world, int color) {circledef shape=new circledef ();//Create Circle Description Object shape.density=2 ; Setting density shape.friction=0.0f; setting friction coefficient shape.restitution=0.95f; Set the energy loss rate shape.radius=radius/rate;//Set the radius bodydef bodydef=new bodydef (); Create a Rigidbody Description object BodyDef.position.set (x/rate,y/rate); Set position body bodytemp=world.createbody (bodydef); Create a rigid body bodytemp.createshape (shape) in the world; Specifies the Rigidbody shape bodytemp.setmassfromshapes ();
Set object quality return to new Mycirclecolor (bodytemp, radius, color);
}
}
(6) Color tool class Colorutil
Package box2d.bheap;
public class Colorutil {
static int[][] result=
{{
56,225,254},
{41,246,239},
{34,244,197},
{44,241,161},
{65,239,106},
{45,238,59},
{73,244,51},
{99,233,58},
{129,243,34},
{142,245,44}
, {187,243,32},
{232,250,28},
{242,230,46},
{248,196,51},
{244,125,31},
{247,88,46},
{249,70,40},
{249,70,40},
{248,48,48},
{250,30,30},
{252,15,15},
{255,0,0},
};
public static int GetColor (int index)
{
int[] rgb=result[index%result.length];
int result=0xff000000;
Result=result| (rgb[0]<<16);
Result=result| (rgb[1]<<8);
Result=result| (Rgb[2]);
return result;
}
(7) Main control class Mybox2dactivity
Package box2d.bheap;
Import java.util.ArrayList;
Import Java.util.Random;
Import Org.jbox2d.collision.AABB;
Import ORG.JBOX2D.COMMON.VEC2;
Import Org.jbox2d.dynamics.World;
Import android.app.Activity;
Import Android.content.pm.ActivityInfo;
Import Android.os.Bundle;
Import Android.util.DisplayMetrics;
Import Android.view.Window;
Import Android.view.WindowManager;
Import static box2d.bheap.constant.*;
The public class Mybox2dactivity extends the activity {AABB worldaabb;//creates a management collision of world worlds;
Random random=new Random ();
Object List arraylist<mybody> bl=new arraylist<mybody> ();
public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Set to Full-screen requestwindowfeature (window.feature_no_title); GetWindow (). SetFlags (Windowmanager.layoutparams. Flag_fullscreen, Windowmanager.layoutparams.
Flag_fullscreen); Set to horizontal screen mode setrequestedorientation (activityinfo.screen_orientation_portrait);
Get screen size displaymetrics dm=new displaymetrics ();
Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM);
if (dm.widthpixels<dm.heightpixels) {screen_width=dm.widthpixels;
Screen_height=dm.heightpixels;
else {screen_width=dm.heightpixels;
Screen_height=dm.widthpixels;
} Worldaabb = new AABB ();
Upper and lower bounds, to the top left of the screen as the origin, if the created rigid body to reach the edge of the screen, will stop the simulation WorldAABB.lowerBound.set ( -100.0f,-100.0f);
WorldAABB.upperBound.set (100.0f, 100.0f);//Note that the real-world unit is used here Vec2 gravity = new VEC2 (0.0f,10.0f);
Boolean dosleep = true;
Create the World = New Worlds (Worldaabb, Gravity, dosleep); Create 4-side final int kd=40;//width or height myrectcolor mrc=box2dutil.createbox (KD/4, SCREEN_HEIGHT/2, KD/4, SCREEN_HEIGHT/2,
TRUE,WORLD,0XFFE6E4FF);
Bl.add (MRC);
Mrc=box2dutil.createbox (SCREEN_WIDTH-KD/4, SCREEN_HEIGHT/2, KD/4, SCREEN_HEIGHT/2, true,world,0xffe6e4ff); Bl.aDD (MRC);
Mrc=box2dutil.createbox (SCREEN_WIDTH/2, KD/4, SCREEN_WIDTH/2, KD/4, true,world,0xffe6e4ff);
Bl.add (MRC);
Mrc=box2dutil.createbox (SCREEN_WIDTH/2, SCREEN_HEIGHT-KD/4, SCREEN_WIDTH/2, KD/4, true,world,0xffe6e4ff);
Bl.add (MRC);
Create a brick//brick spacing line spacing of 20 module width of 10 up to 9 block final int bs=20;
final int bw= (int) ((screen_width-2*kd-11*bs)/18);
============================================================ for (int i=2;i<10;i++) {if (i%2) ==0)
{//Left blue block for (int j=0;j<9-i;j++) {Mrc=box2dutil.createbox ( kd/2+bs+bw/2+i* (kd+5)/2+j* (kd+5) +3, screen_height+bw-i* (BW+KD)/2, BW/2, kd/
2, False, World, Colorutil.getcolor (Math.Abs (Random.nextint ()));
Bl.add (MRC); }//Right blue block for (int j=0;j<9-i;j++) {Mrc=box2dutil.createbox
(3*kd/2+bs-bw/2+i* (kd+5)/2+j* (kd+5) -3, screen_height+bw-i* (BW+KD)/2, BW
/2, KD/2, False, World, Colorutil.getcolor (Math.Abs (Random.nextint ()))
);
Bl.add (MRC); } if ((i%2)!=0) {for (int j=0;j<10-i;j++) {Mrc=box2dutil.createbo
X (kd/2+bs+kd/2+ (i-1) * (kd+5)/2+j* (kd+5), screen_height-(KD-BW)/2-(i-1) * (BW+KD)/2, KD/2, BW/2, False, World, Colorutil.getcolor (Math.Abs (Rando
M.nextint ()));
Bl.add (MRC);
}} mrc=box2dutil.createbox (5*kd+bs+20, screen_height-(KD+BW) *4-KD, BW/2,
KD/2, False, World, Colorutil.getcolor (Math.Abs (Random.nextint ()));
Bl.add (MRC); Create a ball Mycirclecolor Ball=box2Dutil.createcircle (screen_width/2-24, KD, KD/2, World,colorutil.getcolor (Math.Abs (Random.nextint)));
Bl.add (ball);
Ball.body.setLinearVelocity (New VEC2 (0,50));
Gameview gv= New Gameview (this);
Setcontentview (GV);
}
}
(8) Display interface class Gameview
Package box2d.bheap;
Import Android.graphics.Canvas;
Import Android.graphics.Paint;
Import Android.view.SurfaceHolder;
Import Android.view.SurfaceHolder.Callback;
Import Android.view.SurfaceView;
public class Gameview extends Surfaceview implements callback{activity;
Paint Paint;
Drawthread DT;
Public Gameview (mybox2dactivity activity) {super (activity);
this.activity=activity;
This.getholder (). Addcallback (this);
Paint =new paint ();
Paint.setantialias (TRUE);
Dt=new Drawthread (this);
Dt.start ();
public void OnDraw (Canvas Canvas) {if (canvas==null) {return; } canvas.drawargb (255, 255, 255, 255);
Sets the background color white for (mybody mb:activity.bl) {mb.drawself (canvas, paint);
@Override public void surfacechanged (surfaceholder holder, int format, int width, int height) {} @Override public void surfacecreated (Surfaceholder holder) {repaint ();
@Override public void surfacedestroyed (Surfaceholder holder) {} public void repaint () {Surfacehold
Er holder=this.getholder ();
Canvas Canvas=holder.lockcanvas ();
try {synchronized (holder) {OnDraw (canvas);
} catch (Exception e) {e.printstacktrace ();
finally {if (canvas!=null) {holder.unlockcanvasandpost (canvas);
}
}
}
}
(9) Drawing thread class Drawthread
Package box2d.bheap;
Import static box2d.bheap.constant.*;
Draw thread public
class Drawthread extends thread
{
Gameview gv;
Public Drawthread (Gameview GV)
{
this.gv=gv;
}
@Override public
Void Run ()
{while
(Draw_thread_flag)
{
gv.activity.world.step (time_) Step, Itera);//Start simulating
gv.repaint ();
Try
{
thread.sleep;
} catch (Interruptedexception e)
{
e.printstacktrace ()
}}
}
}
I hope this article will help you with the JSP program design.