效果图
/*
* name;
*/
import b2World = Box2D.Dynamics.b2World;
import b2BodyDef = Box2D.Dynamics.b2BodyDef;
import b2Body = Box2D.Dynamics.b2Body;
import b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
import b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
class LaserView extends ui.LaserViewUI{
constructor(){
super();
this.init();
Laya.timer.frameLoop(1,this,this.update);
}
private _world:b2World;
private init():void
{
this.create2bWorld();
this.createb2Body_rectangle(360,400,100,100,b2Body.b2_dynamicBody);
this.createb2Body_rectangle(360,800,1000,100,b2Body.b2_staticBody);
this.b2DebugDraw();
}
private update():void
{
this._world.Step(1/30,10,10);
this._world.DrawDebugData();
}
// 创建物理世界
private create2bWorld():void
{
let gravity:Box2D.Common.Math.b2Vec2 = new Box2D.Common.Math.b2Vec2(0,10); // 重力
let doSleep:boolean = true; // 为 true 时 将静止的刚体标记为随眠状态,在遍历的时候直接跳过去,不进行运动模拟计算,提高了Box2D的计算效率,节省CPU
this._world = new b2World(gravity,doSleep);
}
// 创建一个 矩形刚体
private createb2Body_rectangle(x:number,y:number,width:number,height:number,type:number):void
{
let bd:b2BodyDef = new b2BodyDef(); // b2BodyDef 是b2Body所有属性的一个集合,作用:在刚体创建前,收集所有运动合状态相关属性,然后传入b2Body。
// bd.type = b2Body.b2_dynamicBody; // 设置为 动态
// bd.type = b2Body.b2_staticBody; // 设置为 静态
bd.type = type;
bd.position = new Box2D.Common.Math.b2Vec2(x/30,y/30); //设置位置
let b2_rect:b2PolygonShape = new b2PolygonShape(); // 多边形对象
b2_rect.SetAsBox(width/2/30,height/2/30);
let fd:b2FixtureDef = new b2FixtureDef(); // b2FixtureDef 主要保存了刚体物质特性方面的属性,如形状shape,密度density,表面摩擦力friction,弹性系数restitution等等
fd.shape = b2_rect;
fd.filter.groupIndex = 1;
let body:b2Body = this._world.CreateBody(bd); // 刚体对象
body.CreateFixture(fd);
}
// 2bDebugDraw 调试视图绘制
private b2DebugDraw():void
{
// ----- Laya 绘制 --------
var canvas = Laya.Browser.createElement('canvas');
canvas.width = Laya.stage.width;
canvas.height = Laya.stage.height;
var ctx = canvas.getContext('2d');
Laya.stage.graphics.clear(false);
var textture = new Laya.Texture(canvas);
textture.bitmap.alwaysChange = true; //小游戏使用,非常费,每帧刷新
Laya.stage.graphics.drawTexture(textture);
// box2d
let debugDraw:Box2D.Dynamics.b2DebugDraw = new Box2D.Dynamics.b2DebugDraw();
debugDraw.SetSprite(ctx);
debugDraw.SetDrawScale(30);
debugDraw.SetFlags(Box2D.Dynamics.b2DebugDraw.e_shapeBit|Box2D.Dynamics.b2DebugDraw.e_jointBit);
debugDraw.SetFillAlpha(1);
debugDraw.SetLineThickness(1);
this._world.SetDebugDraw(debugDraw);
}
}