/
physics-manager.ts
313 lines (278 loc) · 11.1 KB
/
physics-manager.ts
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
/****************************************************************************
Copyright (c) 2019 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
import { IPhysicsWorld, IRaycastOptions } from '../spec/i-physics-world';
import { createPhysicsWorld } from './instance';
import { PhysicsMaterial } from './assets/physics-material';
import { PhysicsRayResult } from './physics-ray-result';
const { property, ccclass } = cc._decorator;
/**
* !#en
* Physical systems manager.
* !#zh
* 物理系统管理器。
* @class Physics3DManager
*/
@ccclass("cc.Physics3DManager")
export class Physics3DManager {
/**
* !#en
* Whether to enable the physics system, default is false.
* !#zh
* 是否启用物理系统,默认不启用。
* @property {boolean} enabled
*/
get enabled (): boolean {
return this._enabled;
}
set enabled (value: boolean) {
this._enabled = value;
}
/**
* !#en
* Whether to allow the physics system to automatically hibernate, default is true.
* !#zh
* 物理系统是否允许自动休眠,默认为 true。
* @property {boolean} allowSleep
*/
get allowSleep (): boolean {
return this._allowSleep;
}
set allowSleep (v: boolean) {
this._allowSleep = v;
if (!CC_EDITOR && !CC_PHYSICS_BUILTIN) {
this.physicsWorld.allowSleep = this._allowSleep;
}
}
/**
* !#en
* The maximum number of sub-steps a full step is permitted to be broken into, default is 2.
* !#zh
* 物理每帧模拟的最大子步数,默认为 2。
* @property {number} maxSubStep
*/
get maxSubStep (): number {
return this._maxSubStep;
}
set maxSubStep (value: number) {
this._maxSubStep = value;
}
/**
* !#en
* Time spent in each simulation of physics, default is 1/60s.
* !#zh
* 物理每步模拟消耗的固定时间,默认为 1/60 秒。
* @property {number} deltaTime
*/
get deltaTime (): number {
return this._fixedTime;
}
set deltaTime (value: number) {
this._fixedTime = value;
}
/**
* !#en
* Whether to use a fixed time step.
* !#zh
* 是否使用固定的时间步长。
* @property {boolean} useFixedTime
*/
get useFixedTime (): boolean {
return this._useFixedTime;
}
set useFixedTime (value: boolean) {
this._useFixedTime = value;
}
/**
* !#en
* Gravity value of the physics simulation, default is (0, -10, 0).
* !#zh
* 物理世界的重力数值,默认为 (0, -10, 0)。
* @property {Vec3} gravity
*/
get gravity (): cc.Vec3 {
return this._gravity;
}
set gravity (gravity: cc.Vec3) {
this._gravity.set(gravity);
if (!CC_EDITOR && !CC_PHYSICS_BUILTIN) {
this.physicsWorld.gravity = gravity;
}
}
/**
* !#en
* Gets the global default physical material. Note that builtin is null.
* !#zh
* 获取全局的默认物理材质,注意:builtin 时为 null。
* @property {PhysicsMaterial | null} defaultMaterial
* @readonly
*/
get defaultMaterial (): PhysicsMaterial | null {
return this._material;
}
readonly physicsWorld: IPhysicsWorld;
readonly raycastClosestResult = new PhysicsRayResult();
readonly raycastResults: PhysicsRayResult[] = [];
@property
private _enabled = false;
@property
private _allowSleep = true;
@property
private readonly _gravity = new cc.Vec3(0, -10, 0);
@property
private _maxSubStep = 1;
@property
private _fixedTime = 1.0 / 60.0;
@property
private _useFixedTime = true;
useAccumulator = false;
private _accumulator = 0;
useFixedDigit = false;
useInternalTime = false;
readonly fixDigits = {
position: 5,
rotation: 12,
timeNow: 3,
}
private _deltaTime = 0;
private _lastTime = 0;
private readonly _material: cc.PhysicsMaterial | null = null;
private readonly raycastOptions: IRaycastOptions = {
'groupIndex': -1,
'queryTrigger': true,
'maxDistance': Infinity
}
private readonly raycastResultPool = new cc.RecyclePool(() => {
return new PhysicsRayResult();
}, 1);
private constructor () {
cc.director._scheduler && cc.director._scheduler.enableForTarget(this);
this.physicsWorld = createPhysicsWorld();
this._lastTime = performance.now();
if (!CC_PHYSICS_BUILTIN) {
this.gravity = this._gravity;
this.allowSleep = this._allowSleep;
this._material = new PhysicsMaterial();
this._material.friction = 0.1;
this._material.restitution = 0.1;
this._material.on('physics_material_update', this._updateMaterial, this);
this.physicsWorld.defaultMaterial = this._material;
}
}
/**
* !#en
* A physical system simulation is performed once and will now be performed automatically once per frame.
* !#zh
* 执行一次物理系统的模拟,目前将在每帧自动执行一次。
* @method update
* @param {number} deltaTime The time difference from the last execution is currently elapsed per frame
*/
update (deltaTime: number) {
if (CC_EDITOR) {
return;
}
if (!this._enabled) {
return;
}
if (this.useInternalTime) {
var now = parseFloat(performance.now().toFixed(this.fixDigits.timeNow));
this._deltaTime = now > this._lastTime ? (now - this._lastTime) / 1000 : 0;
this._lastTime = now;
} else {
this._deltaTime = deltaTime;
}
cc.director.emit(cc.Director.EVENT_BEFORE_PHYSICS);
if (CC_PHYSICS_BUILTIN) {
this.physicsWorld.step(this._fixedTime);
} else {
if (this._useFixedTime) {
this.physicsWorld.step(this._fixedTime);
} else {
if (this.useAccumulator) {
let i = 0;
this._accumulator += this._deltaTime;
while (i < this._maxSubStep && this._accumulator > this._fixedTime) {
this.physicsWorld.step(this._fixedTime);
this._accumulator -= this._fixedTime;
i++;
}
} else {
this.physicsWorld.step(this._fixedTime, this._deltaTime, this._maxSubStep);
}
}
}
cc.director.emit(cc.Director.EVENT_AFTER_PHYSICS);
}
/**
* !#en Detect all collision boxes and return all detected results, or null if none is detected. Note that the return value is taken from the object pool, so do not save the result reference or modify the result.
* !#zh 检测所有的碰撞盒,并返回所有被检测到的结果,若没有检测到,则返回空值。注意返回值是从对象池中取的,所以请不要保存结果引用或者修改结果。
* @method raycast
* @param {Ray} worldRay A ray in world space
* @param {number|string} groupIndexOrName Collision group index or group name
* @param {number} maxDistance Maximum detection distance
* @param {boolean} queryTrigger Detect trigger or not
* @return {PhysicsRayResult[] | null} Detected result
*/
raycast (worldRay: cc.geomUtils.Ray, groupIndexOrName: number | string = 0, maxDistance = Infinity, queryTrigger = true): PhysicsRayResult[] | null {
this.raycastResultPool.reset();
this.raycastResults.length = 0;
if (typeof groupIndexOrName == "string") {
let groupIndex = cc.game.groupList.indexOf(groupIndexOrName);
if (groupIndex == -1) groupIndex = 0;
this.raycastOptions.groupIndex = groupIndex;
} else {
this.raycastOptions.groupIndex = groupIndexOrName;
}
this.raycastOptions.maxDistance = maxDistance;
this.raycastOptions.queryTrigger = queryTrigger;
let result = this.physicsWorld.raycast(worldRay, this.raycastOptions, this.raycastResultPool, this.raycastResults);
if (result) return this.raycastResults;
return null;
}
/**
* !#en Detect all collision boxes and return the detection result with the shortest ray distance. If not, return null value. Note that the return value is taken from the object pool, so do not save the result reference or modify the result.
* !#zh 检测所有的碰撞盒,并返回射线距离最短的检测结果,若没有,则返回空值。注意返回值是从对象池中取的,所以请不要保存结果引用或者修改结果。
* @method raycastClosest
* @param {Ray} worldRay A ray in world space
* @param {number|string} groupIndexOrName Collision group index or group name
* @param {number} maxDistance Maximum detection distance
* @param {boolean} queryTrigger Detect trigger or not
* @return {PhysicsRayResult|null} Detected result
*/
raycastClosest (worldRay: cc.geomUtils.Ray, groupIndexOrName: number | string = 0, maxDistance = Infinity, queryTrigger = true): PhysicsRayResult | null {
if (typeof groupIndexOrName == "string") {
let groupIndex = cc.game.groupList.indexOf(groupIndexOrName);
if (groupIndex == -1) groupIndex = 0;
this.raycastOptions.groupIndex = groupIndex;
} else {
this.raycastOptions.groupIndex = groupIndexOrName;
}
this.raycastOptions.maxDistance = maxDistance;
this.raycastOptions.queryTrigger = queryTrigger;
let result = this.physicsWorld.raycastClosest(worldRay, this.raycastOptions, this.raycastClosestResult);
if (result) return this.raycastClosestResult;
return null;
}
private _updateMaterial () {
if (!CC_PHYSICS_BUILTIN) {
this.physicsWorld.defaultMaterial = this._material;
}
}
}