Box2D教程5碰撞检测.docx
《Box2D教程5碰撞检测.docx》由会员分享,可在线阅读,更多相关《Box2D教程5碰撞检测.docx(24页珍藏版)》请在冰豆网上搜索。
![Box2D教程5碰撞检测.docx](https://file1.bdocx.com/fileroot1/2023-4/24/4ce945f3-18f4-4d41-8e7c-a6fc3dbc6bf6/4ce945f3-18f4-4d41-8e7c-a6fc3dbc6bf61.gif)
Box2D教程5碰撞检测
大伦子de空间
转载来源:
ComingX
原文链接:
Box2D教程5-碰撞检测
——————————————–
之前我们已经了解了如何通过Box2D创建一个物理世界,给刚体添加复杂材质,鼠标交互。
在游戏开发里面我们通常要判断两个物体相互碰撞了,然后进行相应的操作。
比如“愤怒的小鸟”,当小鸟碰撞到箱子的时候,我们需要知道这两个物体碰撞了,然后判断碰撞的力度(后面的教程会讲),然后对箱子进行操作。
这个教程就是用来处理Box2D的碰撞检测问题。
这个教程仍然基于先前的教程,关于如何创建一个物理世界,这里就不解释了。
为了要实现碰撞检测,需要使用到Box2D的B2ContactListener类。
该类是一个抽象类,不能直接被实例化,它包含四个方法:
BeginContact,EndContact,PreSolve,PostSolve,我们必须先继承它创建自定义的ContactListener,然后override你需要的方法。
这个教程主要检测两个物体产生碰撞以及碰撞结束。
因此我们overrideBeginContact(开始碰撞)和EndContact(碰撞结束)方法。
首先我们创建一个简单的物理世界,四个边框和三个球体,这在先前的教程有详细说明
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package
{
importBox2D.Collision.Shapes.b2CircleShape;
importBox2D.Collision.Shapes.b2PolygonShape;
importBox2D.Collision.Shapes.b2Shape;
importBox2D.Collision.b2AABB;
importBox2D.Common.Math.b2Vec2;
importBox2D.Dynamics.Joints.b2MouseJoint;
importBox2D.Dynamics.Joints.b2MouseJointDef;
importBox2D.Dynamics.b2Body;
importBox2D.Dynamics.b2BodyDef;
importBox2D.Dynamics.b2DebugDraw;
importBox2D.Dynamics.b2Fixture;
importBox2D.Dynamics.b2FixtureDef;
importBox2D.Dynamics.b2World;
importmon.Console;
importmon.CustomContactListener;
importcomingx.jingle.events.CollisionEvent;
importcomingx.jingle.userdata.BallUserData;
importflash.display.GradientType;
importflash.display.Sprite;
importflash.events.Event;
importflash.events.MouseEvent;
importflash.geom.Matrix;
importflash.text.TextField;
importflash.text.TextFieldAutoSize;
importflash.text.TextFormat;
[SWF(width="500",height="300",frameRate="30")]
publicclassBox2DCheckCollisionextendsSprite
{
//屏幕像素单位转换成物理世界的距离单位
privateconstPIXEL_TO_METER:
Number=30;
//物理世界
privatevarworld:
Box2D.Dynamics.b2World;
privatevar_mouseXWorldPhys:
Number;
privatevar_mouseYWorldPhys:
Number;
privatevar_mouseXWorld:
Number;
privatevar_mouseYWorld:
Number;
privatevar_mousePVec:
b2Vec2=newb2Vec2();
privatevar_groundBody:
b2Body;
privatevar_mouseJoint:
b2MouseJoint;
privatevarmouseDown:
Boolean=false;
privatevarconsole:
Console;
publicfunctionBox2DCheckCollision()
{
drawBackground();
createWorld();
createWall();
createBall();
createDebugDraw();
addEventListener(Event.ENTER_FRAME,handleEnterFrame);
addEventListener(MouseEvent.MOUSE_DOWN,handleMouseDown);
addEventListener(MouseEvent.MOUSE_UP,handleMouseUp);
addEventListener(MouseEvent.CLICK,handleMouseUp);
addEventListener(Event.MOUSE_LEAVE,handleMouseUp);
}
privatefunctioncreateWorld():
void
{
//重力向量
vargravity:
b2Vec2=newb2Vec2(0,9.0);
//是否休眠
vardoSleep:
Boolean=true;
world=newb2World(gravity,doSleep);
world.SetWarmStarting(true);
}
privatefunctioncreateWall():
void
{
//1.需要创建的墙刚体
varleftWall:
b2Body;
//2.刚体定义
varleftWallBodyDef:
b2BodyDef=newb2BodyDef();
//刚体类型和位置
leftWallBodyDef.type=b2Body.b2_staticBody;
//注意刚体的注册中心都是在物体的中心位置
leftWallBodyDef.position.Set(10/PIXEL_TO_METER,stage.stageHeight/2/PIXEL_TO_METER);
//工厂模式创建刚体
leftWall=world.CreateBody(leftWallBodyDef);
//3.刚体修饰物定义
varleftWallFixtureDef:
b2FixtureDef=newb2FixtureDef();
//密度
leftWallFixtureDef.density=1.0;
//摩擦粗糙程度
leftWallFixtureDef.friction=0.3;
//力度返回程度(弹性)
leftWallFixtureDef.restitution=1.0;
//4.创建墙形状
varleftWallShape:
b2PolygonShape=newb2PolygonShape();
//此处参数为宽和高度的一半值
leftWallShape.SetAsBox(10/PIXEL_TO_METER,stage.stageHeight/2/PIXEL_TO_METER);
//将形状添加到刚体修饰物
leftWallFixtureDef.shape=leftWallShape;
leftWall.CreateFixture(leftWallFixtureDef);
//下面创建其他三面墙,共用leftwall的几个变量
leftWallBodyDef.position.Set((stage.stageWidth-10)/PIXEL_TO_METER,stage.stageHeight/2/PIXEL_TO_METER);
varrightWall:
b2Body=world.CreateBody(leftWallBodyDef);
rightWall.CreateFixture(leftWallFixtureDef);
leftWallBodyDef.position.Set(stage.stageWidth/2/PIXEL_TO_METER,(stage.stageHeight-10)/PIXEL_TO_METER);
varbottomWall:
b2Body=world.CreateBody(leftWallBodyDef);
leftWallShape.SetAsBox(stage.stageWidth/2/PIXEL_TO_METER,10/PIXEL_TO_METER);
bottomWall.CreateFixture(leftWallFixtureDef);
leftWallBodyDef.position.Set(stage.stageWidth/2/PIXEL_TO_METER,10/PIXEL_TO_METER);
vartopWall:
b2Body=world.CreateBody(leftWallBodyDef);
topWall.CreateFixture(leftWallFixtureDef);
}
privatefunctioncreateBall():
void
{
varballDef:
b2BodyDef=newb2BodyDef();
ballDef.type=b2Body.b2_dynamicBody;
ballDef.position.Set(50/PIXEL_TO_METER,30/PIXEL_TO_METER);
varballBig:
b2Body=world.CreateBody(ballDef);
varcircleShape:
b2CircleShape=newb2CircleShape(30/PIXEL_TO_METER);
varballFixtureDef:
b2FixtureDef=newb2FixtureDef();
ballFixtureDef.shape=circleShape;
ballFixtureDef.density=1.0;
ballFixtureDef.restitution=0.5;
ballBig.CreateFixture(ballFixtureDef);
ballDef.position.Set(200/PIXEL_TO_METER,30/PIXEL_TO_METER);
varballMedium:
b2Body=world.CreateBody(ballDef);
circleShape=newb2CircleShape(20/PIXEL_TO_METER);
ballFixtureDef.shape=circleShape;
ballMedium.CreateFixture(ballFixtureDef);
ballDef.position.Set(400/PIXEL_TO_METER,30/PIXEL_TO_METER);
varballSmall:
b2Body=world.CreateBody(ballDef);
circleShape=newb2CircleShape(15/PIXEL_TO_METER);
ballFixtureDef.shape=circleShape;
ballSmall.CreateFixture(ballFixtureDef);
}
privatefunctioncreateDebugDraw():
void
{
//创建一个sprite,可以将测试几何物体放入其中
vardebugSprite:
Sprite=newSprite();
addChild(debugSprite);
vardebugDraw:
b2DebugDraw=newb2DebugDraw();
debugDraw.SetSprite(debugSprite);
//设置边框厚度
debugDraw.SetLineThickness(1.0);
//边框透明度
debugDraw.SetAlpha(1.0);
//填充透明度
debugDraw.SetFillAlpha(0.5);
//设置显示对象
debugDraw.SetFlags(b2DebugDraw.e_shapeBit);
//物理世界缩放
debugDraw.SetDrawScale(PIXEL_TO_METER);
world.SetDebugDraw(debugDraw);
}
privatefunctionhandleEnterFrame(evt:
Event):
void
{
UpdateMouseWorld();
mouseDrag();
vartimeStep:
Number=1/30;
varvelocityInterations:
int=10;
varpositionIterations:
int=10;
world.Step(timeStep,velocityInterations,positionIterations);
//在2.1版本清除力,以提高效率
world.ClearForces();
//绘制
world.DrawDebugData();
}
privatefunctiondrawBackground():
void
{
varbg:
Sprite=newSprite();
varmatrix:
Matrix=newMatrix();
matrix.translate(100,100);
bg.graphics.beginGradientFill(GradientType.RADIAL,[0xffffff,0xffaa00],[0.3,0.2],[0,255],matrix);
bg.graphics.drawRect(0,0,stage.stageWidth,stage.stage.stageHeight);
bg.graphics.endFill();
addChild(bg);
//tips
vartf:
TextField=newTextField();
tf.text="拖动球产生碰撞";
tf.autoSize=TextFieldAutoSize.LEFT;
varfomat:
TextFormat=newTextFormat("Kai,华文楷体","20",0x555555);
tf.setTextFormat(fomat);
tf.x=tf.y=30;
addChild(tf);
}
privatefunctionUpdateMouseWorld():
void
{
_mouseXWorldPhys=this.mouseX/PIXEL_TO_METER;
_mouseYWorldPhys=this.mouseY/PIXEL_TO_METER;
_mouseXWorld=this.mouseX;
_mouseYWorld=this.mouseY;
}
privatefunctiongetBodyAtMouse(includeStatic:
Boolean=false):
b2Body
{
_mousePVec.Set(_mouseXWorldPhys,_mouseYWorldPhys);
varaabb:
b2AABB=newb2AABB();
aabb.lowerBound.Set(_mouseXWorldPhys-0.001,_mouseYWorldPhys-0.001);
aabb.upperBound.Set(_mouseXWorldPhys+0.001,_mouseYWorldPhys+0.001);
varbody:
b2Body=null;
varfixture:
b2Fixture;
functiongetBodyCallback(fixture:
b2Fixture):
Boolean
{
varshape:
b2Shape=fixture.GetShape();
if(fixture.GetBody().GetType()!
=b2Body.b2_staticBody||includeStatic)
{
varinside:
Boolean=shape.TestPoint(fixture.GetBody().GetTransform(),_mousePVec);
if(inside)
{
body=fixture.GetBody();
returnfalse;
}
}
returntrue;
}
world.QueryAABB(getBodyCallback,aabb);
returnbody;
}
privatefunctionmouseDrag():
void
{
if(mouseDown&&!
_mouseJoint)
{
varbody:
b2Body=getBodyAtMouse();
if(body)
{
varmd:
b2MouseJointDef=newb2MouseJointDef();
md.bodyA=world.GetGroundBody();
md.bodyB=body;
md.target.Set(_mouseXWorldPhys,_mouseYWorldPhys);
md.collideConnected=true;
md.maxForce=300.0*body.GetMass();
_mouseJoint=