forked from ar2rsawseen/GiderosCodingEasy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Box2dEasy.lua
606 lines (532 loc) · 15.8 KB
/
Box2dEasy.lua
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
--[[
PHYSICS EXTENSIONS
]]--
function loadPhysicsExtension()
--implementing vectors
b2.Vect = Core.class()
--create new vector from 2 points (A starting point and B ending point)
function b2.Vect:init(startX, startY, endX, endY)
self.startX = startX
self.startY = startY
self.endX = endX
self.endY = endY
self.xVect = startX - endX
self.yVect = startY - endY
end
--get vector on x axis
function b2.Vect:getX()
return self.xVect
end
--get vector on y axis
function b2.Vect:getY()
return self.yVect
end
--get the length of the vector (distance between A and B points)
function b2.Vect:getLength()
if not self.length then
self.length = math.sqrt(self.xVect*self.xVect + self.yVect*self.yVect)
end
return self.length
end
--get the angle of vector (angle for AB line, when up is 0 radians)
function b2.Vect:getAngle()
if not self.angle then
self.angle = math.acos(self.yVect/(self:getLength()))
if(self.xVect > 0) then
self.angle = -self.angle
end
end
return self.angle
end
--get point on AB vector with provided distance from point A
function b2.Vect:getPoint(fromDistance)
local ratio = math.sqrt((fromDistance*fromDistance)/(self.xVect*self.xVect + self.yVect*self.yVect))
local endX = self.startX + self.xVect*ratio
local endY = self.startY + self.yVect*ratio
return endX, endY
end
b2.World._new = b2.World.new
function b2.World.new(...)
local world = b2.World._new(...)
world.sprites = {}
world.curSprite = 1
world.beginCallbacks = {}
world.endCallbacks = {}
world:addEventListener(Event.BEGIN_CONTACT, world._handleBeginContact, world)
world:addEventListener(Event.END_CONTACT, world._handleEndContact, world)
return world
end
function b2.World:_handleBeginContact(e)
--getting contact bodies
local fixtureA = e.fixtureA
local fixtureB = e.fixtureB
local bodyA = fixtureA:getBody()
local bodyB = fixtureB:getBody()
local collisionHandler
if self.beginCallbacks[bodyA] and self.beginCallbacks[bodyA][bodyB] then
collisionHandler = self.beginCallbacks[bodyA][bodyB]
object1 = bodyA.object
object2 = bodyB.object
elseif self.beginCallbacks[bodyB] and self.beginCallbacks[bodyB][bodyA] then
collisionHandler = self.beginCallbacks[bodyB][bodyA]
object1 = bodyB.object
object2 = bodyA.object
end
if collisionHandler then
if collisionHandler.data then
collisionHandler.callback(collisionHandler.data, object1, object2, e)
else
collisionHandler.callback(object1, object2, e)
end
end
end
function b2.World:_handleEndContact(e)
--getting contact bodies
local fixtureA = e.fixtureA
local fixtureB = e.fixtureB
local bodyA = fixtureA:getBody()
local bodyB = fixtureB:getBody()
local collisionHandler, object1, object2
if self.endCallbacks[bodyA] and self.endCallbacks[bodyA][bodyB] then
collisionHandler = self.endCallbacks[bodyA][bodyB]
object1 = bodyA.object
object2 = bodyB.object
elseif self.endCallbacks[bodyB] and self.endCallbacks[bodyB][bodyA] then
collisionHandler = self.endCallbacks[bodyB][bodyA]
object1 = bodyB.object
object2 = bodyA.object
end
if collisionHandler then
if collisionHandler.data then
collisionHandler.callback(collisionHandler.data, object1, object2, e)
else
collisionHandler.callback(object1, object2, e)
end
end
end
function b2.World:addBeginContact(object1, object2, callback, data)
local body1 = object1.body
local body2 = object2.body
if not self.beginCallbacks[body1] then
self.beginCallbacks[body1] = {}
end
if not self.beginCallbacks[body1][body2] then
self.beginCallbacks[body1][body2] = {}
end
local t = {}
t.callback = callback
if data then
t.data = data
end
self.beginCallbacks[body1][body2] = t
return self
end
function b2.World:addEndContact(object1, object2, callback, data)
local body1 = object1.body
local body2 = object2.body
if not self.endCallbacks[body1] then
self.endCallbacks[body1] = {}
end
if not self.endCallbacks[body1][body2] then
self.endCallbacks[body1][body2] = {}
end
local t = {}
t.callback = callback
if data then
t.data = data
end
self.endCallbacks[body1][body2] = t
return self
end
function b2.World:makeDraggable(object)
--create empty box2d body for joint
--since mouse cursor is not a body
--we need dummy body to create joint
local ground = self:createBody({})
--joint with dummy body
local mouseJoint = nil
-- create a mouse joint on mouse down
object.onDragStart = function(self, event)
if object:hitTestPoint(event.touch.x, event.touch.y) then
local jointDef = b2.createMouseJointDef(ground, object.body,
event.touch.x, event.touch.y, 100000)
mouseJoint = self:createJoint(jointDef)
end
end
-- update the target of mouse joint on mouse move
object.onDragMove = function(self, event)
if mouseJoint ~= nil then
mouseJoint:setTarget(event.touch.x, event.touch.y)
end
end
-- destroy the mouse joint on mouse up
object.onDragEnd = function(self, event)
if mouseJoint ~= nil then
self:destroyJoint(mouseJoint)
mouseJoint = nil
end
end
-- register for mouse events
object:addEventListener(Event.TOUCHES_BEGIN, object.onDragStart, self)
object:addEventListener(Event.TOUCHES_MOVE, object.onDragMove, self)
object:addEventListener(Event.TOUCHES_END, object.onDragEnd, self)
return self
end
function b2.World:undoDraggable(object)
-- register for mouse events
object:removeEventListener(Event.TOUCHES_BEGIN, object.onDragStart, self)
object:removeEventListener(Event.TOUCHES_MOVE, object.onDragMove, self)
object:removeEventListener(Event.TOUCHES_END, object.onDragEnd, self)
object.onDragStart = nil
object.onDragMove = nil
object.onDragEnd = nil
return self
end
function b2.World:__enchanceObject(object)
--local body = object.body
for k,v in pairs(b2.Body) do
if type(v) == "function" and not object[k] then
if (k:sub(1, 3) == "set" or k:sub(1, 5) == "apply" or k:sub(1, 7) == "destroy") then
object[k] = function(self, ...)
object.body[k](object.body, ...)
return self
end
else
object[k] = function(self, ...)
return object.body[k](object.body, ...)
end
end
end
end
for k,v in pairs(b2.Fixture) do
if type(v) == "function" and not object[k] then
if (k:sub(1, 3) == "set" or k:sub(1, 5) == "apply" or k:sub(1, 7) == "destroy") then
object[k] = function(self, ...)
object.body[k](object.body, ...)
return self
end
else
object[k] = function(self, ...)
return object.body[k](object.body, ...)
end
end
end
end
end
function b2.World:createRectangle(object, config)
local conf = {
type = "static",
density = 1.0,
friction = 1.0,
restitution = 0.2,
update = true,
draggable = false,
width = nil,
height = nil,
isSensor = false
}
if config then
--copying configuration
for key,value in pairs(config) do
conf[key]= value
end
end
if object and conf.update then
object.id = self.curSprite
self.sprites[object.id] = object
self.curSprite = self.curSprite + 1
end
local setType = b2.STATIC_BODY
if conf.type == "dynamic" then
setType = b2.DYNAMIC_BODY
elseif conf.type == "kinematic" then
setType = b2.KINEMATIC_BODY
end
--create box2d physical object
local body = self:createBody{type = setType}
conf.shape = "rectangle"
body._conf = conf
local angle
if object then
angle = object:getRotation()
object:setRotation(0)
end
conf.width = conf.width or object:getWidth()
conf.height = conf.height or object:getHeight()
local poly = b2.PolygonShape.new()
poly:setAsBox(conf.width/2, conf.height/2)
local fixture = body:createFixture{shape = poly, density = conf.density,
friction = conf.friction, restitution = conf.restitution, isSensor = conf.isSensor}
body._fixture = fixture
if object then
if getmetatable(object) ~= MovieClip then
object:setAnchorPoint(0.5, 0.5)
end
body:setPosition(object:getX(), object:getY())
body:setAngle(math.rad(angle))
object.body = body
body.object = object
if conf.type == "dynamic" and conf.draggable then
self:makeDraggable(object)
end
object:setRotation(angle)
self:__enchanceObject(object)
end
body.userdata = {}
body.joints = {}
return self
end
function b2.World:createCircle(object, config)
local conf = {
type = "static",
density = 1.0,
friction = 1.0,
restitution = 0.2,
update = true,
draggable = false,
radius = nil,
isSensor = false
}
if config then
--copying configuration
for key,value in pairs(config) do
conf[key]= value
end
end
if object and conf.update then
object.id = self.curSprite
self.sprites[object.id] = object
self.curSprite = self.curSprite + 1
end
local setType = b2.STATIC_BODY
if conf.type == "dynamic" then
setType = b2.DYNAMIC_BODY
elseif conf.type == "kinematic" then
setType = b2.KINEMATIC_BODY
end
--create box2d physical object
local body = self:createBody{type = setType}
conf.shape = "circle"
body._conf = conf
local angle
if object then
angle = object:getRotation()
object:setRotation(0)
end
conf.radius = conf.radius or object:getWidth()/2
local circle = b2.CircleShape.new(0, 0, conf.radius)
local fixture = body:createFixture{shape = circle, density = conf.density,
friction = conf.friction, restitution = conf.restitution, isSensor = conf.isSensor}
body._fixture = fixture
if object then
if getmetatable(object) ~= MovieClip then
object:setAnchorPoint(0.5, 0.5)
end
body:setPosition(object:getX(), object:getY())
body:setAngle(math.rad(angle))
object.body = body
body.object = object
if conf.type == "dynamic" and conf.draggable then
self:makeDraggable(object)
end
object:setRotation(angle)
self:__enchanceObject(object)
end
body.userdata = {}
body.joints = {}
return self
end
function b2.World:createTerrain(object, vertices, config)
local conf = {
type = "static",
density = 1.0,
friction = 1.0,
restitution = 0.2,
update = true,
draggable = false,
isSensor = false
}
if config then
--copying configuration
for key,value in pairs(config) do
conf[key]= value
end
end
if object and conf.update then
object.id = self.curSprite
self.sprites[object.id] = object
self.curSprite = self.curSprite + 1
end
local setType = b2.STATIC_BODY
if conf.type == "dynamic" then
setType = b2.DYNAMIC_BODY
elseif conf.type == "kinematic" then
setType = b2.KINEMATIC_BODY
end
--create box2d physical object
local body = self:createBody{type = setType}
conf.shape = "terrain"
body._conf = conf
local chain = b2.ChainShape.new()
chain:createChain(unpack(vertices))
conf.vertices = vertices
local fixture = body:createFixture{shape = chain, density = conf.density,
friction = conf.friction, restitution = conf.restitution, isSensor = conf.isSensor}
body._fixture = fixture
if object then
body:setPosition(object:getX(), object:getY())
body:setAngle(math.rad(object:getRotation()))
object.body = body
body.object = object
if conf.type == "dynamic" and conf.draggable then
self:makeDraggable(object)
end
self:__enchanceObject(object)
end
body.userdata = {}
body.joints = {}
return self
end
function b2.World:update()
-- edit the step values if required. These are good defaults!
self:step(1/60, 8, 3)
--iterate through all child sprites
local sprites = #self.sprites
for i = 1, sprites do
--get specific sprite
local sprite = self.sprites[i]
-- check if sprite HAS a body (ie, physical object reference we added)
if sprite.body then
--update position to match box2d world object's position
--get physical body reference
local body = sprite.body
--get body coordinates
local bodyX, bodyY = body:getPosition()
--apply coordinates to sprite
sprite:setPosition(bodyX, bodyY)
--apply rotation to sprite
sprite:setRotation(math.deg(body:getAngle()))
end
end
return self
end
function b2.World:getDebug()
--set up debug drawing
local debugDraw = b2.DebugDraw.new()
debugDraw:setFlags(b2.DebugDraw.SHAPE_BIT + b2.DebugDraw.JOINT_BIT)
self:setDebugDraw(debugDraw)
return debugDraw
end
function b2.World:removeBody(object, destroy)
if object.body then
if object.id then
self.sprites[object.id] = nil
end
Timer.delayedCall(1, function()
self:destroyBody(object.body)
end)
object.body = nil
if destroy then
object:removeFromParent()
end
end
return self
end
function b2.Body:setData(key, value)
self.userdata[key] = value
return self
end
function b2.Body:getData(key)
return self.userdata[key]
end
function b2.Body:set(param, val)
if param == "x" then
local x, y = self:getPosition()
self:setPosition(val, y)
elseif param == "y" then
local x, y = self:getPosition()
self:setPosition(x, val)
elseif param == "rotation" then
self:setAngle(math.rad(val))
elseif param == "scaleBody" then
self._scale = val
if self._conf.shape == "rectangle" then
self:destroyFixture(self._fixture)
local poly = b2.PolygonShape.new()
poly:setAsBox((self._conf.width/2)*self._scale, (self._conf.height/2)*self._scale)
local fixture = self:createFixture{shape = poly, density = self._conf.density,
friction = self._conf.friction, restitution = self._conf.restitution, isSensor = self._conf.isSensor}
self._fixture = fixture
elseif self._conf.shape == "circle" then
self:destroyFixture(self._fixture)
local circle = b2.CircleShape.new(0, 0, self._conf.radius*self._scale)
local fixture = self:createFixture{shape = circle, density = self._conf.density,
friction = self._conf.friction, restitution = self._conf.restitution, isSensor = self._conf.isSensor}
self._fixture = fixture
end
if self.object then
self.object:setScale(self._scale)
end
else
local m = param:gsub("^%l", string.upper) -- convert linearVelocity to LinearVelocity
if self["set"..m] ~= nil then
self["set"..m](self, val)
else --lets check for x or y on the end as in linearVelocityX
local last = string.lower(m:sub(string.len(m))) --get last character
local m = m:sub(1, string.len(m)-1) -- get LinearVelocity from LinearVelocityX
if self["set"..m] ~= nil and (last == "x" or last == "y") then
local x, y = self["get"..m](self) -- get x and y values
if last == "x" then
self["set"..m](self, val, y)
elseif last == "y" then
self["set"..m](self, x, val)
end
end
end
end
end
function b2.Body:get(param)
if param == "x" then
local x, y = self:getPosition()
return x
elseif param == "y" then
local x, y = self:getPosition()
return y
elseif param == "rotation" then
return math.deg(self:getAngle())
elseif param == "scaleBody" then
return self._scale or 1
else
local m = param:gsub("^%l", string.upper) -- convert linearVelocity to LinearVelocity
if self["get"..m] ~= nil then
return self["get"..m](self)
else --lets check for x or y on the end as in linearVelocityX
local last = string.lower(m:sub(string.len(m))) --get last character
local m = m:sub(1, string.len(m)-1) -- get LinearVelocity from LinearVelocityX
if self["get"..m] ~= nil and (last == "x" or last == "y") then
local x, y = self["get"..m](self) -- get x and y values
if last == "x" then
return x
elseif last == "y" then
return y
end
end
end
end
end
end
--[[ catching the load of box2d ]]--
if b2 == nil then
local _require = require
require = function(name)
local answer = _require(name)
if name == "box2d" then
-- load box2d extensions
loadPhysicsExtension()
require = _require
end
return answer
end
else
loadPhysicsExtension()
end