本教程为大家介绍如何利用P2物理引擎实现Egret官方物理小球的示例效果。
修改egretProperties.json,modules数组里增加
{
“name”:”physics”,
“path”:”../physics”
}
然后找到插件-Egret项目工具-编译引擎编译一下就成功引入P2库。
使用P2物理引擎创建物理应用的过程大致分为5个步骤:
1. 创建world世界
2. 创建shape形状
3. 创建body刚体
4. 实时调用step()函数,更新物理模拟计算
5. 基于形状、刚体,使用Egret渲染,显示物理模拟效果
接下来根据这5个步骤进行代码构建
//创建Word世界
private world:p2.World;
private CreateWorld(){
this.world = new p2.World();
//设置world为睡眠状态
this.world.sleepMode = p2.World.BODY_SLEEPING;
this.world.gravity = [0,1]
}
gravity是一个Vector2向量对象,表示world世界中重力加速度,默认为垂直向上的向量[0,-9.81],将gravity设置为[0,0]可以取消重力;gravity的x分量也是有意义的,将其设置为一个非0数值后,重力就会朝向量[x,y]方向。
//生成地板Plane
private planeBody:p2.Body;
private CreatePlane(){
//创建一个shape形状
let planeShape:p2.Plane = new p2.Plane();
//创建body刚体
this.planeBody= new p2.Body({
//刚体类型
type:p2.Body.STATIC,
//刚体的位置
position:[0,this.stage.stageHeight]
});
this.planeBody.angle = Math.PI;
this.planeBody.displays = [];
this.planeBody.addShape(planeShape);
this.world.addBody(this.planeBody);
}
Plane相当于地面,默认面向Y轴方向。
因为这个Y轴是P2的Y轴,而不是Egret的Y轴。P2和Egret的Y轴是相反的。所以将地面翻转180度。planeBody.angle = Math.PI
private shpeBody:p2.Body;
//贴图显示对象
private display:egret.DisplayObject;
private onButtonClick(e:egret.TouchEvent) {
if(Math.random() >0.5){
//添加方形刚体
var boxShape:p2.Shape = new p2.Box({width:140 ,height:80});
this.shpeBody = new p2.Body({ mass: 1, position: [e.stageX, e.stageY], angularVelocity: 1});
this.shpeBody.addShape(boxShape);
this.world.addBody(this.shpeBody);
this. display= this.createBitmapByName("rect_png");
this.display.width = (.Box>boxShape).width
this.display.height = (.Box>boxShape).height
}
else{
//添加圆形刚体
var circleShape:p2.Shape = new p2.Circle({radius:60});
this.shpeBody = new p2.Body({ mass: 1, position: [e.stageX, e.stageY]});
this.shpeBody.addShape(circleShape);
this.world.addBody(this.shpeBody);
this.display = this.createBitmapByName("circle_png");
this.display.width = (.Circle>circleShape).radius * 2
this.display.height = (.Circle>circleShape).radius * 2
}
this.display.anchorOffsetX = this.display.width / 2
this.display.anchorOffsetY = this.display.height / 2;
this.display.x = -100;
this.display.y = -100;
this.display.rotation = 270
this.shpeBody.displays = [this.display];
this.addChild(this.display);
}
上述代码中先创建Box或者Circle形状,并通过addShape()函数,将其添加到刚体body中,最后通过world的addBody()将刚体添加到世界中,完成一个P2物理应用创建。
**注意:**Egret中加载进来的图像,其原点默认为左上角,而P2中刚体的原点处于其中心位置,如下图(盗了一张图)
所以需要根据刚体重心坐标偏移量(offsetX,offsetY)设置图像的anchorOffsetX ,anchorOffsetY 属性。
//帧事件,步函数
private update() {
this.world.step(2.5);
var l = this.world.bodies.length;
for (var i:number = 0; i < l; i++) {
var boxBody:p2.Body = this.world.bodies[i];
var box:egret.DisplayObject = boxBody.displays[0];
if (box) {
//将刚体的坐标和角度赋值给显示对象
box.x = boxBody.position[0];
box.y = boxBody.position[1];
box.rotation = boxBody.angle * 180 / Math.PI;
//如果刚体当前状态为睡眠状态,将图片alpha设为0.5,否则为1
if (boxBody.sleepState == p2.Body.SLEEPING) {
box.alpha = 0.5;
}
else {
box.alpha = 1;
}
}
}
}
world中所有的刚体都保存在属性bodies数组中,通过数组的foreach()方法,可以遍历其中的每一个body,然后拿到body的显示对象,再将刚体的坐标和角度属性赋值给显示对象,实时更新即可。
protected createGameScene(): void {
let img:egret.Bitmap = new egret.Bitmap();
img = this.createBitmapByName("bg_jpg");
img.width = this.stage.stageWidth;
img.height = this.stage.stageHeight;
this.addChild(img);
this.CreateWorld();
this.CreatePlane();
this.addEventListener(egret.Event.ENTER_FRAME,this.update,this);
this.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.onButtonClick,this);
}
最后贴上所有代码
class Main extends eui.UILayer {
protected createChildren(): void {
super.createChildren();
egret.lifecycle.addLifecycleListener((context) => {
// custom lifecycle plugin
})
egret.lifecycle.onPause = () => {
egret.ticker.pause();
}
egret.lifecycle.onResume = () => {
egret.ticker.resume();
}
//inject the custom material parser
//注入自定义的素材解析器
let assetAdapter = new AssetAdapter();
egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());
this.runGame().catch(e => {
console.log(e);
})
}
private async runGame() {
await this.loadResource()
this.createGameScene();
const result = await RES.getResAsync("description_json")
await platform.login();
const userInfo = await platform.getUserInfo();
console.log(userInfo);
}
private async loadResource() {
try {
const loadingView = new LoadingUI();
this.stage.addChild(loadingView);
await RES.loadConfig("resource/default.res.json", "resource/");
await this.loadTheme();
await RES.loadGroup("preload", 0, loadingView);
this.stage.removeChild(loadingView);
}
catch (e) {
console.error(e);
}
}
private loadTheme() {
return new Promise((resolve, reject) => {
// load skin theme configuration file, you can manually modify the file. And replace the default skin.
//加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
let theme = new eui.Theme("resource/default.thm.json", this.stage);
theme.addEventListener(eui.UIEvent.COMPLETE, () => {
resolve();
}, this);
})
}
private textfield: egret.TextField;
/**
* 创建场景界面
* Create scene interface
*/
protected createGameScene(): void {
let img:egret.Bitmap = new egret.Bitmap();
img = this.createBitmapByName("bg_jpg");
img.width = this.stage.stageWidth;
img.height = this.stage.stageHeight;
this.addChild(img);
this.CreateWorld();
this.CreatePlane();
this.addEventListener(egret.Event.ENTER_FRAME,this.update,this);
this.stage.addEventListener(egret.TouchEvent.TOUCH_BEGIN,this.onButtonClick,this);
}
//创建Word世界
private world:p2.World;
private CreateWorld(){
this.world = new p2.World();
this.world.sleepMode = p2.World.BODY_SLEEPING;
this.world.gravity = [0,10]
}
//生成地板Plane
private planeBody:p2.Body;
private CreatePlane(){
let planeShape:p2.Plane = new p2.Plane();
this.planeBody= new p2.Body({
type:p2.Body.STATIC,
position:[0,this.stage.stageHeight],
});
this.planeBody.angle = Math.PI;
this.planeBody.displays = [];
this.planeBody.addShape(planeShape);
this.world.addBody(this.planeBody);
}
private shpeBody:p2.Body;
private display:egret.DisplayObject;
private onButtonClick(e:egret.TouchEvent) {
if(Math.random() >0.5){
//添加方形刚体
var boxShape:p2.Shape = new p2.Box({width:140 ,height:80});
this.shpeBody = new p2.Body({ mass: 1, position: [e.stageX, e.stageY], angularVelocity: 1});
this.shpeBody.addShape(boxShape);
this.world.addBody(this.shpeBody);
this. display= this.createBitmapByName("rect_png");
this.display.width = (.Box>boxShape).width
this.display.height = (.Box>boxShape).height
console.log(e.stageX,e.stageY);
}
else{
//添加圆形刚体
var circleShape:p2.Shape = new p2.Circle({radius:60});
this.shpeBody = new p2.Body({ mass: 1, position: [e.stageX, e.stageY]});
this.shpeBody.addShape(circleShape);
this.world.addBody(this.shpeBody);
this.display = this.createBitmapByName("circle_png");
this.display.width = (.Circle>circleShape).radius * 2
this.display.height = (.Circle>circleShape).radius * 2
}
this.display.anchorOffsetX = this.display.width / 2
this.display.anchorOffsetY = this.display.height / 2;
this.display.x = -100;
this.display.y = -100;
this.display.rotation = 270
this.shpeBody.displays = [this.display];
this.addChild(this.display);
}
//帧事件,步函数
private update() {
this.world.step(1);
var l = this.world.bodies.length;
for (var i:number = 0; i < l; i++) {
var boxBody:p2.Body = this.world.bodies[i];
var box:egret.DisplayObject = boxBody.displays[0];
if (box) {
box.x = boxBody.position[0];
box.y = boxBody.position[1];
//这里刷新图片旋转
box.rotation = boxBody.angle * 180 / Math.PI;
if (boxBody.sleepState == p2.Body.SLEEPING) {
box.alpha = 0.5;
}
else {
box.alpha = 1;
}
}
}
}
/**
* 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
*/
private createBitmapByName(name:string):egret.Bitmap {
var result:egret.Bitmap = new egret.Bitmap();
var texture:egret.Texture = RES.getRes(name);
result.texture = texture;
return result;
}
}