-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
executable file
·104 lines (87 loc) · 2.84 KB
/
index.js
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
/**
* @author notchris <[email protected]>
* @copyright 2020 notchris
* @license @link https://github.com/notchris/phaser3-planck
*/
import Phaser from 'phaser'
import * as Planck from 'planck-js'
import Sprite from './src/classes/Sprite'
export default class PhaserPlanck extends Phaser.Plugins.ScenePlugin {
constructor(scene, pluginManager) {
super(scene, pluginManager)
let config = scene.registry.parent.config.physics.planck
if (scene.registry.parent.config.physics.planck) {
let scaleFactor = config.scaleFactor
let gravity = config.gravity
if (!scaleFactor) {
scaleFactor = 30
}
if (!gravity) {
gravity = { x: 0, y: 0 }
}
config = {
debug: config.debug ? true : false,
scaleFactor,
gravity,
}
}
Phaser.Physics.PhaserPlanck = this
this.scene = scene
this.world = new Planck.World(Planck.Vec2(config.gravity.x, config.gravity.y))
this.sprites = []
this.scaleFactor = config.scaleFactor
scene.planck = this
if (!scene.sys.settings.isBooted) {
scene.sys.events.once("boot", this.boot, this)
}
// Creates a sprite with an empty Planck body
this.add = {
sprite: (x, y, texture) => {
const s = new Sprite(this.scene, x, y, texture)
this.sprites.push(s)
return s
}
}
// Planck event bindings
this.world.on('pre-solve', (contact, oldManifold) => {
this.sprites.forEach((s) => s.preSolve(contact, oldManifold))
})
this.world.on('post-solve', (contact, oldManifold) => {
this.sprites.forEach((s) => s.postSolve(contact, oldManifold))
})
this.world.on('begin-contact', (contact, oldManifold) => {
const a = this.sprites.filter((s) => s.fixture === contact.getFixtureA())[0]
const b = this.sprites.filter((s) => s.fixture === contact.getFixtureB())[0]
a.emit('collision-start', b)
b.emit('collision-start', a)
})
this.world.on('end-contact', (contact, oldManifold) => {
const a = this.sprites.filter((s) => s.fixture === contact.getFixtureA())[0]
const b = this.sprites.filter((s) => s.fixture === contact.getFixtureB())[0]
a.emit('collision-end', b)
b.emit('collision-end', a)
})
}
boot() {
const eventEmitter = this.systems.events
eventEmitter.on("update", this.update, this)
eventEmitter.on("postupdate", this.postUpdate, this)
eventEmitter.on("shutdown", this.shutdown, this)
eventEmitter.on("destroy", this.destroy, this)
}
postUpdate() {}
update() {
this.world.step(1 / 60)
this.world.clearForces()
}
shutdown() {
}
destroy() {
this.shutdown()
this.scene = undefined
this.sprites = []
}
}
PhaserPlanck.register = function(PluginManager) {
PluginManager.register("PhaserPlanck", PhaserPlanck, "PhaserPlanck")
}