您的位置:首页 > 移动开发 > Cocos引擎

Cocos2D-Android-1之源码详解:5.Box2dTest

2015-12-09 17:07 471 查看
package org.cocos2d.tests;

import java.util.Iterator;

import org.cocos2d.actions.UpdateCallback;
import org.cocos2d.config.ccMacros;
import org.cocos2d.events.CCTouchDispatcher;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCLabel;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.nodes.CCSpriteSheet;
import org.cocos2d.opengl.CCGLSurfaceView;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGRect;
import org.cocos2d.types.CGSize;
import org.cocos2d.types.ccColor3B;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.EdgeShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;

/**
* A test that demonstrates basic JBox2D integration by using AtlasSprites connected to physics bodies.
* <br/>
* <br/>
* This implementation is based on the original Box2DTest (from cocos2d-iphone) but using the JBox2D
* library and adjusting for differences with the new API as well as some differences in sensitivity
* (and such) that were observed when testing on the Android platform.
*
* @author Ray Cardillo
*/
// Box2dTest, there is a downloadable demo here:
// http://code.google.com/p/cocos2d-android-1/downloads/detail?name=cocos2d%20%20and%20jbox2d.3gp&can=2&q=#makechanges //
public class Box2dTest extends Activity {//物理盒子系统
// private static final String LOG_TAG = JBox2DTest.class.getSimpleName();

static {
System.loadLibrary("gdx");//加载一个gdx库
}

private CCGLSurfaceView mGLSurfaceView;//创建一个view

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//无标题
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);//全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//不黑屏

mGLSurfaceView = new CCGLSurfaceView(this);//生成view,并关联上下文到导演
CCDirector director = CCDirector.sharedDirector();//生成得到导演(唯一)
director.attachInView(mGLSurfaceView);//把view交给导演的list
director.setDeviceOrientation(CCDirector.kCCDeviceOrientationLandscapeLeft);//横屏
setContentView(mGLSurfaceView);//把view映射刀屏幕

// show FPS
CCDirector.sharedDirector().setDisplayFPS(true);//显示帧频率

// frames per second
CCDirector.sharedDirector().setAnimationInterval(1.0f / 60.0f);//帧速

CCScene scene = CCScene.node();//得到一个场景
scene.addChild(new Box2DTestLayer());//把一个box的图层添加到场景里

// Make the Scene active
CCDirector.sharedDirector().runWithScene(scene);//让导演运行这个场景,运行到刚才的view中
}

@Override
public void onStart() {//开始方法
super.onStart();

}

@Override
public void onPause() {//暂停方法
super.onPause();

CCDirector.sharedDirector().onPause();
}

@Override
public void onResume() {
super.onResume();

CCDirector.sharedDirector().onResume();
}

@Override
public void onDestroy() {//销毁方法
super.onDestroy();

CCDirector.sharedDirector().end();
//CCTextureCache.sharedTextureCache().removeAllTextures();
}

//
// Demo of calling integrating Box2D physics engine with cocos2d sprites
// a cocos2d example
// http://code.google.com/p/cocos2d-iphone //
// by Steve Oldmeadow
//
static class Box2DTestLayer extends CCLayer {//以下是这个方法生成的方法
public static final int kTagTileMap = 1;
public static final int kTagSpriteManager = 1;
public static final int kTagAnimation1 = 1;

// Pixel to meters ratio. Box2D uses meters as the unit for measurement.
// This ratio defines how many pixels correspond to 1 Box2D "meter"
// Box2D is optimized for objects of 1x1 meter therefore it makes sense
// to define the ratio so that your most common object type is 1x1 meter.
protected static final float PTM_RATIO = 32.0f;

// Simulation space should be larger than window per Box2D recommendation.
protected static final float BUFFER = 1.0f;

//FPS for the PhysicsWorld to sync to
protected static final float FPS = (float)CCDirector.sharedDirector().getAnimationInterval();//得到整个动画的帧频率
private static float rdelta = 0;

protected final World bxWorld;//生成一个世界的引用..

public Box2DTestLayer() {//构造方法
super();

this.setIsTouchEnabled(true);//可以点击
this.setIsAccelerometerEnabled(true);//启用设置加速,加速控制器可以启动

CGSize s = CCDirector.sharedDirector().winSize();//得到屏幕的大小引用

// Define the gravity vector.
Vector2 gravity = new Vector2(9.8f, -9.8f);//定义一个二维向量

float scaledWidth = s.width/PTM_RATIO;//缩放宽
float scaledHeight = s.height/PTM_RATIO;//缩放高

// Vector2 lower = new Vector2(-BUFFER, -BUFFER);//更小
// Vector2 upper = new Vector2(scaledWidth+BUFFER, scaledHeight+BUFFER);//更大

bxWorld = new World(gravity, true);//新建并设置这个世界的重力向量
bxWorld.setContinuousPhysics(true);//连续物理可用

// Define the ground body.
BodyDef bxGroundBodyDef = new BodyDef();//定义地面身体
bxGroundBodyDef.position.set(0.0f, 0.0f);//身体的位置

// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
Body groundBody = bxWorld.createBody(bxGroundBodyDef);//将身体添加到世界

// Define the ground box shape.
EdgeShape groundBox = new EdgeShape();//定义一个形状

Vector2 bottomLeft = new Vector2(0f,0f);//定义4个2维向量
Vector2 topLeft = new Vector2(0f,scaledHeight);
Vector2 topRight = new Vector2(scaledWidth,scaledHeight);
Vector2 bottomRight = new Vector2(scaledWidth,0f);

// bottom
groundBox.set( bottomLeft, bottomRight );//设置一条线
groundBody.createFixture(groundBox,0);//把这条线作为物理盒子的边界

// top
groundBox.set( topLeft, topRight );//同理
groundBody.createFixture(groundBox,0);

// left
groundBox.set( topLeft, bottomLeft );
groundBody.createFixture(groundBox,0);

// right
groundBox.set( topRight, bottomRight );
groundBody.createFixture(groundBox,0);

//Set up sprite
CCSpriteSheet mgr = CCSpriteSheet.spriteSheet("blocks.png", 150);
//建立一个图像表单,用来拆分出小块
addChild(mgr, 0, kTagSpriteManager);//表单添加进去,顺序0,把标签号定为1

addNewSpriteWithCoords(CGPoint.ccp(s.width / 2.0f, s.height / 2.0f));
//上面是一个方法下面解释
CCLabel label = CCLabel.makeLabel("Tap screen", "DroidSans", 32);//创建一个标记
label.setPosition(CGPoint.make(s.width / 2f, s.height - 50f));//设置坐标
label.setColor(new ccColor3B(0, 0, 255));//设置颜色
addChild(label);
}

private UpdateCallback tickCallback = new UpdateCallback() {//创建一个时间返回

@Override
public void update(float d) {//时间更新
tick(d);
}
};

@Override
public void onEnter() {
super.onEnter();

// start ticking (for physics simulation)
schedule(tickCallback);
}

@Override
public void onExit() {
super.onExit();

// stop ticking (for physics simulation)
unschedule(tickCallback);
}

private void addNewSpriteWithCoords(CGPoint pos) {
CCSpriteSheet sheet = (CCSpriteSheet) getChildByTag(kTagSpriteManager);//得到一个表格

//We have a 64x64 sprite sheet with 4 different 32x32 images. The following code is
//just randomly picking one of the images
int idx = (ccMacros.CCRANDOM_0_1() > .5 ? 0:1);//定义一个随机数。得到1/0
int idy = (ccMacros.CCRANDOM_0_1() > .5 ? 0:1);

// CCSprite sprite = CCSprite.sprite("blocks.png", CGRect.make(32 * idx,32 * idy,32,32));//生成一个精灵。用那个图片,截取公式位置的图像
// this.addChild(sprite);//添加精灵
CCSprite sprite = CCSprite.sprite(sheet, CGRect.make(32 * idx,32 * idy,32,32));//生成精灵,用刚才的那个图集,截取某块
sheet.addChild(sprite);//添加子类

sprite.setPosition(pos); //设置点

// Define the dynamic body.
//Set up a 1m squared box in the physics world
BodyDef bodyDef = new BodyDef();//新建一个刚体
bodyDef.type = BodyType.DynamicBody;//设置为类型3动态刚体
bodyDef.position.set(pos.x/PTM_RATIO, pos.y/PTM_RATIO);//设置身体位置

// Define another box shape for our dynamic body.
PolygonShape dynamicBox = new PolygonShape();//新建多边形

dynamicBox.setAsBox(.5f, .5f);//These are mid points for our 1m box
//作为一个盒子时的顶点0.5,0.5
// dynamicBox.density = 1.0f;
// dynamicBox.friction = 0.3f;

synchronized (bxWorld) {//线程锁
// Define the dynamic body fixture and set mass so it's dynamic.
Body body = bxWorld.createBody(bodyDef);//在世界内创建这个刚体
body.setUserData(sprite);//使用这个数据精灵

FixtureDef fixtureDef = new FixtureDef();//固定的东西
fixtureDef.shape = dynamicBox;
fixtureDef.density = 1.0f;//密度
fixtureDef.friction = 0.3f;//摩擦系数
body.createFixture(fixtureDef);//把这些固定参数给这个物体
}
}

public synchronized void tick(float delta) {//时间类
if ((rdelta += delta) < FPS) return;//计算得不用快过帧..

// It is recommended that a fixed time step is used with Box2D for stability
// of the simulation, however, we are using a variable time step here.
// You need to make an informed choice, the following URL is useful
// http://gafferongames.com/game-physics/fix-your-timestep/
// Instruct the world to perform a simulation step. It is
// generally best to keep the time step and iterations fixed.
synchronized (bxWorld) {
bxWorld.step(FPS, 8, 1);//计算的速度
}

rdelta = 0;//累计时间

// Iterate over the bodies in the physics world
Iterator<Body> it = bxWorld.getBodies();//新建迭代器得到世界的刚体集合
while(it.hasNext()) {
Body b = it.next();//得到刚体
Object userData = b.getUserData();//刚体的数据

if (userData != null && userData instanceof CCSprite) {
//如果数据不为空,且是个精灵的实例而
//Synchronize the Sprites position and rotation with the corresponding body
final CCSprite sprite = (CCSprite)userData;//得到这个图像
final Vector2 pos = b.getPosition();//得到这个刚体的点
sprite.setPosition(pos.x * PTM_RATIO, pos.y * PTM_RATIO);
//设置点
sprite.setRotation(-1.0f * ccMacros.CC_RADIANS_TO_DEGREES(b.getAngle()));//设置弧度
}
}
}

@Override
public boolean ccTouchesBegan(MotionEvent event) {//触屏事件
CGPoint location = CCDirector.sharedDirector()
.convertToGL(CGPoint.make(event.getX(), event.getY()));//得到点

addNewSpriteWithCoords(location);//添加一个物品在那个点

return CCTouchDispatcher.kEventHandled;//返回数据
}

static float prevX=0, prevY=0;

Vector2 gravity = new Vector2();//定义2维数组

@Override
public void ccAccelerometerChanged(float accelX, float accelY, float accelZ) {//当加速传感器有感觉了

//#define kFilterFactor 0.05f
float kFilterFactor = 1.0f; // don't use filter. the code is here just as an example

float accX = (float) accelX * kFilterFactor + (1- kFilterFactor)* prevX;//x方向
float accY = (float) accelY * kFilterFactor + (1- kFilterFactor)* prevY;//y方向

prevX = accX;
prevY = accY;

// no filtering being done in this demo (just magnify the gravity a bit)
gravity.set( accY * 9.8f, accX * -9.8f );//得到重力的向量
bxWorld.setGravity( gravity ); //给世界设置重力向量
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: