P2物理引擎——物理小球案例
本教程为大家介绍如何利用P2物理引擎实现Egret官方物理小球的示例效果。
- 第三方库的引入
- 创建一个P2物理项目
1. 第三方库的引入
- 首先新建一个项目。
- 在GitHub上下载包括P2物理引擎库的完整第三方库,解压后按照路径找到physics模块。
- 将physics模块放到新建项目根目录的同级目录。
修改egretProperties.json,modules数组里增加
{
“name”:”physics”,
“path”:”../physics”
}然后找到插件-Egret项目工具-编译引擎编译一下就成功引入P2库。
2.创建一个P2物理项目
使用P2物理引擎创建物理应用的过程大致分为5个步骤:
1. 创建world世界
2. 创建shape形状
3. 创建body刚体
4. 实时调用step()函数,更新物理模拟计算
5. 基于形状、刚体,使用Egret渲染,显示物理模拟效果
接下来根据这5个步骤进行代码构建
1.打开Main.ts,首先创建world世界
//创建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]方向。
2.创建地板Plane
//生成地板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
3.点击创建足球或者矩形方块
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 = (<p2.Box>boxShape).width
this.display.height = (<p2.Box>boxShape).height
}
else{
//添加圆形刚体
var circleShape:p2.Shape = new p2.Circle({radius:60});
this.shpeBody = new p2