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

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

发布时间:2020-08-06 06:19:28

来源:51CTO

阅读:398

作者:abab99

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.

*

*

* 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 p_w_picpaths.  The following code is

//just randomly picking one of the p_w_picpaths

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

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 );//给世界设置重力向量

}

}

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/526945.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

三星s10能升级android11,三星 S10+手机已在测试 Android 11 系统

IT之家2月25日消息 谷歌本月初发布了首个Android 11开发者预览版&#xff0c;首先面向Pixel手机&#xff0c;不过看起来三星已经在Galaxy S10 手机开始测试最新系统。IT之家从Geekbench数据库中获知&#xff0c;上面出现了运行Android R&#xff0c;型号为SM-G975F的三星Galaxy…

android 5. 蓝牙 mesh,蓝牙mesh组网

智能照明是智能家居的一个重要入口&#xff0c;传统照明方案存在布线复杂&#xff0c;控制单一等问题。搭配飞易通MESH组网模组替换传统方案&#xff0c;无需额外的布线。提供更智能的控制&#xff0c;更极致的用户体验。一、MESH应用领域:蓝牙5.0MESH是由SIG蓝牙联盟发布建立的…

android opencv 银行卡识别,NDK 开发之使用 OpenCV 实现银行卡号识别

前言在日常的开发中&#xff0c;我们有时会遇到添加银行卡的需求&#xff0c;这时候&#xff0c;产品可能会让你仿一下支付宝之类的相机扫描识别银行卡号。很多时候&#xff0c;做这样的需求会去找找稳定的第三方&#xff0c;本文通过 OpenCV 结合识别的需求带你分析如何实现银…

鸿蒙测试机型微博,华为多款机型开启鸿蒙尝鲜:微博已适配HarmonyOS小尾巴

日前&#xff0c;华为已经正式宣布&#xff0c;将于6月2日晚20点召开鸿蒙操作系统及华为全场景新品发布会&#xff0c;届时将正式发布鸿蒙OS正式版。同时&#xff0c;今天华为还开启了鸿蒙OS首批消费者尝鲜计划&#xff0c;其中正式版可参与机型包括Mate 40系列、Mate X2、Mate…

android今日头条刷新,仿今日头条刷新vector动画

一般的刷新动画是一个圈圈在转&#xff0c;而头条的比较特殊&#xff0c;直接上写好的效果图(一直不知道怎么把图片尺寸调小o(╯□╰)o)吧~刷新动画_.gif首先整个效果是通过SVG和vector来实现的&#xff0c;如果不是很了解&#xff0c;请看大佬的文章&#xff1a;SVG学习--Anim…

android懒加载单实例,【 Android 10 设计模式 】系列 -- 单例

前言由于源码分析的代码量比较大&#xff0c;大部分博客网站的内容显示页面都比较窄&#xff0c;显示出来的效果都异常丑陋&#xff0c;所以您也可以直接查看 《 Thinking in Android 》 来阅读这边文章&#xff0c;希望这篇文章能帮你梳理清楚 “ 单例模式 ”。一、概述1.1 什…

android资产目录,android – 从非目录设备中的资产文件夹复制数据库

我正在尝试从资产文件夹将数据库复制到设备.此代码在模拟器和根设备上正常工作.我只是想知道是否在无人看管的设备上创建任何问题,否则它会相同.private void StoreDatabase() {File DbFile new File("data/data/packagename/DBname.sqlite");if (DbFile.exists()) …

在html中标题字号一共有几种,HTML中常用的几种标签

在HTML中&#xff0c;标签是首要的&#xff0c;也是最重要的东西。一旦进入HTML&#xff0c;认识和理解标签是基本的需要&#xff0c;因为这是区分HTML代码与普通文本的分隔符。这些标签是用来显示文档中的普通文本或转化文本的指令的标签。什么是转化后的文本&#xff1f;要显…

html静态页面引用其他页面,Shtml完美解决静态页面内部调用其他页面(非Iframe、Object、Js方法)...

我想这个是所有前端工程师都会碰到的问题&#xff0c;在你做了很多页面&#xff0c;需要调用同一个头部或者底部的时候&#xff0c;需要嵌套一下&#xff0c;这个时候怎么办Iframe、Object、Js调用的方法就不讨论了&#xff0c;网上搜索一大堆&#xff0c;不过兼容性不好这里给…

鸿蒙手机如何录屏,安卓手机如何屏幕录制视屏?手机视频录制方法

安卓手机如何屏幕录制视屏&#xff1f;手机视频录制方法2018年12月17日 17:05作者&#xff1a;黄页编辑&#xff1a;黄页分享随着科技的不断进步发展,手机已经成为人类不可缺少的一种生活神器,人们已经不满足只是用来打打电话、发发短信那么简单了,手机的用途主要用来社交、娱乐…

html判断为空的函数,javascript怎么判断是否为空字符串?

JavaScript中可以使用if(typeof obj"undefined"||objnull||obj"")语句通过判断字符串的数据类型来判断字符串是否为空。判断字符串是否为空的方法函数&#xff1a;function isEmpty(obj){if(typeof obj "undefined" || obj null || obj "…

html或原生js是单一对应绑定的,原生js数据绑定

双向数据绑定是非常重要的特性 —— 将JS模型与HTML视图对应&#xff0c;能减少模板编译时间同时提高用户体验。我们将学习在不使用框架的情况下&#xff0c;使用原生JS实现双向绑定 —— 一种为Object.observe_(译注&#xff1a;现已废弃&#xff0c;作者写博客时为14年11月)&…

et200sp模块接线手册_西门子PN/PN耦合器学习应用系列(1)-外观及接线

早在2017年我曾写过两篇文章介绍西门子PN/PN耦合器&#xff0c;文章链接如下&#xff1a;初识西门子PNPN耦合器(PN/PN Coupler)&#xff1b;如何在博途(TIA Portal)环境下组态PNPN耦合器&#xff1f;当时PN/PN耦合器的固件版本还是V3.x。随着产品的升级&#xff0c;新版本的PN/…

textview加载html glide,TextView加载HTML,文字和图片

原文出处链接&#xff1a;《TextView加载HTML&#xff0c;文字和图片》工具类&#xff1a;public class ImageGetterUtils {public static MyImageGetter getImageGetter(Context context, TextView textView) {MyImageGetter myImageGetter new MyImageGetter(context, textV…

js 条码枪扫描_年会展台 精彩不断 | 沧田:从打印到扫描录入 国产品牌从未停止...

11月23日-25日&#xff0c;中国现代办公行业年会(以下简称COAA年会)在南昌召开。今年对于OA行业而言&#xff0c;国产品牌的崛起成为主要特征之一。以针式打印机起家的沧田&#xff0c;在本次展会中展示了多款重量级产品&#xff0c;涵盖了针式打印机、激光一体机、条码打印机、…

投后管理岗面试_2020天津水务招79人,管理岗+操作岗,专科起报

Hello大家好&#xff0c;我们今天的国企招聘主要说的是天津水务。天津水务的公告和去年相比晚了几个月&#xff0c;而且要求也变了一些——变成了校招&#xff08;要求2020年应届生&#xff09;&#xff0c;虽然条件还是不高——大专起报。2点要求基本的条件就是要求&#xff1…

html的课设作业6,第七节课html标签元素属性作业-2019-9-6 作业

实例html>2019最新课程表table {/* border: 1px solid #000; *//* border-collapse: collapse; */width: 800px;margin: 2px auto;border-spacing: 0;/* box-shadow: 2px 2px 2px #888888; */}th,td {/* border: 1px solid #000; */text-align: center;padding: 10px;border…

微信没有回车键怎么换行_在东平相亲网加了心仪对方的微信,但是没有话题怎么办?...

最近很多东平单身小伙伴问红娘&#xff1a;加了对方微信不知道聊什么&#xff0c;觉得两个人没有共同话题&#xff0c;而且感觉该聊的都聊了&#xff0c;每天早晚安也发了&#xff0c;够热情了。还有的说不知道怎么回信息或者不知道跟ta说什么话题该怎么办&#xff1f;1其实这些…

中国重汽微服务管理_springcloud微服务架构实战:商家管理微服务设计

商家管理微服务设计商家管理微服务是一个独立的RESTAPI应用&#xff0c;这个应用通过接口服务对外提供商家信息管理、商家权限管理和菜单资源管理等方面的功能。商家管理微服务开发在merchant-restapi模块中实现&#xff0c;有关这一类型模块的依赖引用、配置、启动程序的设计等…

计算机自带游戏在哪里打开,电脑自带游戏选项在哪里打开

如果只是这个游戏有这个问题&#xff0c;就是软件有问题了&#xff0c;重装这游戏&#xff0c;如果有好几个软件都有这个问题&#xff0c;无疑是中毒了&#xff0c;用360彻底查杀。不行重装系统&#xff0c;装完后马上装360&#xff0c;再升级查杀。重装游戏。不行就-------那是…