Box2d learning for Android (2)-simple running and jumping game model (including code)

Source: Internet
Author: User

Address: http://blog.csdn.net/you_and_me12/article/details/8248529


2012-12-02

Since learning box2d for a period of time, I have a preliminary understanding. I wanted to do a simple game exercise, but I was too busy (and too lazy) to continue. Share the code now. Don't spray it, don't hit it! For more information, see.

Feeling: box2d is the engine of the physical world. It seems that the game runs slowly as it does not use so much logic to make a small game. It is still appropriate for games with a large number of physical world views (the angry laruence ).


The article provides some code and model, and finally provides the corresponding code

Build a box2d Environment

See: box2d learning for Android (1) -- helloworld


Game Code framework

Description: It is divided into four modules: general abstract classes, main game threads, objects, and scenarios.

(PS: I have built it myself, which can be subdivided or expanded. Learning about game programming ......)


Mainactivity. Java

This is the main interface of the app and is mainly used to switch the interface and other main operation frameworks.

Description: defines constants, identifiers, game interface surfaceview classes, create scenarios, startup threads, and so on.

public class MainActivity extends Activity {/**the width and height of screen*/public static float gScreenW, gScreenH;/**the global world time step*/public static final float g_STEP_TIME = 1f/60f;/**the handler of view going*/private Handler mHandler;/**the view*/private MainView mMainView;/**game state*/public static final int GAME_STATE_RUNNING = 1, GAME_STATE_PAUSE = 2, GAME_STATE_OVER = 3;    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);gScreenW = getWindowManager().getDefaultDisplay().getWidth();gScreenH = getWindowManager().getDefaultDisplay().getHeight();mHandler = new Handler();mMainView = new MainView(this);setContentView(mMainView);    }    @Overrideprotected void onResume() {super.onResume();mHandler.post(mMainView);}@Overrideprotected void onPause() {super.onPause();mHandler.removeCallbacks(mMainView);}/**     *      * @author K     *     */    public class MainView extends SurfaceView implements SurfaceHolder.Callback, Runnable{    private SurfaceHolder mSurfaceHolder;    private Canvas mCanvas;    private Context mContext;    //    private CommonScene mScene;    /**test now*/    //private CommonScene mSceneBg;public MainView(Context context) {super(context);mContext = context;setKeepScreenOn(true);setFocusable(true);setFocusableInTouchMode(true);mSurfaceHolder = getHolder();mSurfaceHolder.addCallback(this);//create scenemScene = new GameScene(mContext);//init data of the viewmScene.create();//mSceneBg.create();}@Overridepublic void surfaceCreated(SurfaceHolder holder) {//start handlermHandler.postDelayed(this, (long) (g_STEP_TIME*1000));}@Overridepublic void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}@Overridepublic void surfaceDestroyed(SurfaceHolder holder) {mHandler.removeCallbacks(this);}/** * every is running here */@Overridepublic void run() {long start, end;start = System.currentTimeMillis();mScene.step();//go to next stepif(mScene instanceof GameScene) {GameScene gs = (GameScene)mScene;if(gs.getmGameState() == MainActivity.GAME_STATE_OVER) {return;//the world stop}}//mSceneBg.step();try{mCanvas = mSurfaceHolder.lockCanvas();mCanvas.drawColor(Color.BLACK);/**need to draw bg image*/mScene.draw(mCanvas);//mSceneBg.draw(mCanvas);mSurfaceHolder.unlockCanvasAndPost(mCanvas);}catch(Exception e){e.printStackTrace();}end = System.currentTimeMillis();if(end - start < 0)System.out.println("end-start:" + (end-start));//for testmHandler.postDelayed(this, (long) (g_STEP_TIME*1000) - (end - start));}@Overridepublic boolean onTouchEvent(MotionEvent event) {mScene.onTouchEvent(event);return true;}    }}

Commonsence. Java

This is an abstract class for game scenarios and defines general interfaces.

Creation, drawing, iteration, touch screen and other functional interfaces, mainly for mainactivity calls

public abstract class CommonScene {/** common use: the context of activity*/protected Context mContext;/** * constructor * @param context */public CommonScene(Context context){mContext = context;}/** * create and init */abstract public void create();/** * the logic go to next step */abstract public void step();/** * draw the view */abstract public void draw(Canvas canvas);/** * on touch */abstract public boolean onTouchEvent(MotionEvent event);/** * the logic go to next n step */public void step(int n){while(n-- != 0){step();}}}

Commonbody. Java

This is an abstract class for game objects (figures, floors, etc.) and defines general interfaces.

As it is only a preliminary game model, there are only interfaces for creating, plotting, and detecting and destroying the game.

public abstract class CommonBody {/**create the body by world, and return the body*/abstract public Body createByWorld(World world);/**draw the body*/abstract public void draw(Canvas canvas, Paint paint);/**check if the body is out of screen, will remove from the world*/abstract public boolean isOutScreen();}

Implementation of scenarios and objects

For more information, see the code research. It is constructed by Square.


Collision Detection

This is mainly implemented in the scenario where different scenarios have different game designs. There is also the collision listener of objects (the following code). It was initially written, but it is useless. Let's study it !!!

public class GameContactListener implements ContactListener{@Overridepublic void beginContact(Contact contact) {Body bodyA = contact.getFixtureA().getBody();Body bodyB = contact.getFixtureB().getBody();if(bodyA.getUserData() instanceof Person && bodyB.getUserData() instanceof Ground){}}@Overridepublic void endContact(Contact contact) {Body bodyA = contact.getFixtureA().getBody();Body bodyB = contact.getFixtureB().getBody();if(bodyA.getUserData() instanceof Person && bodyB.getUserData() instanceof Ground){}}@Overridepublic void postSolve(Contact contact, ContactImpulse arg1) {}@Overridepublic void preSolve(Contact arg0, Manifold arg1) {}}

Game Introduction

This simple model mainly refers to the world's downward gravity, which is constantly moving forward by the character, while the mobile phone interface keeps the X coordinate of the character's position unchanged, achieving the simulation of moving forward. A jump speed is given. (No rendering, see smile)


Code: http://download.csdn.net/detail/you_and_me12/4837127


Conclusion: I) box2d is made up of the physical world. It is very powerful and hard to learn;

Ii) I am busy with my work and have no time to study. In fact, I am also lazy;

Iii) do not make anything a reason for your not learning );

Iv) learning! This article is intended for you to learn from and learn from each other due to poor technical skills!

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.