cannon-es-control
Version:
A lightweight 3D physics engine written in JavaScript with control system tools
64 lines (54 loc) • 1.57 kB
text/typescript
import { Broadphase } from '../collision/Broadphase'
import type { AABB } from '../collision/AABB'
import type { Body } from '../objects/Body'
import type { World } from '../world/World'
/**
* Naive broadphase implementation, used in lack of better ones.
*
* The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 _(which is bad)_
*/
export class NaiveBroadphase extends Broadphase {
/**
* @todo Remove useless constructor
*/
constructor() {
super()
}
/**
* Get all the collision pairs in the physics world
*/
collisionPairs(world: World, pairs1: Body[], pairs2: Body[]): void {
const bodies = world.bodies
const n = bodies.length
let bi
let bj
// Naive N^2 ftw!
for (let i = 0; i !== n; i++) {
for (let j = 0; j !== i; j++) {
bi = bodies[i]
bj = bodies[j]
if (!this.needBroadphaseCollision(bi, bj)) {
continue
}
this.intersectionTest(bi, bj, pairs1, pairs2)
}
}
}
/**
* Returns all the bodies within an AABB.
* @param result An array to store resulting bodies in.
*/
aabbQuery(world: World, aabb: AABB, result: Body[] = []): Body[] {
for (let i = 0; i < world.bodies.length; i++) {
const b = world.bodies[i]
if (b.aabbNeedsUpdate) {
b.updateAABB()
}
// Ugly hack until Body gets aabb
if (b.aabb.overlaps(aabb)) {
result.push(b)
}
}
return result
}
}