SAT 2D
by jmcjc5u
HTML
<div id="info">SAT 2D
</div>
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://jyunming-chen.github.io/tutsplus/js/KeyboardState.js"></script>
CSS
#info {
position: absolute;
top: 0px;
width: 100%;
padding: 10px;
text-align: center;
color: #ffff00
}
body {
overflow: hidden;
}
JavaScript
var camera, scene, renderer;
var keyboard;
var obb1, obb2;
class Rect2D {
constructor(pos, size, colorName = 'white') {
this.center = pos;
this.size = size; // array of halfwidth's
this.mesh = new THREE.Mesh(new THREE.PlaneGeometry(size[0] * 2, size[1] * 2), new THREE.MeshBasicMaterial({
color: colorName
}));
scene.add(this.mesh);
this.mesh.position.copy(pos);
this.rotate(0); // set initial axes
}
rotate(angle) {
this.angle = angle;
let zAxis = new THREE.Vector3(0, 0, 1);
this.axes = [];
this.axes[0] = (new THREE.Vector3(1, 0, 0)).applyAxisAngle(zAxis, angle);
this.axes[1] = (new THREE.Vector3(0, 1, 0)).applyAxisAngle(zAxis, angle);
this.mesh.rotation.z = angle;
}
intersect(obbB) {
// four axes to check
let obbA = this;
let sepAxes = [];
sepAxes[0] = obbA.axes[0];
sepAxes[1] = obbA.axes[1];
sepAxes[2] = obbB.axes[0];
sepAxes[3] = obbB.axes[1];
let t = obbB.center.clone().sub(obbA.center);
for (let i = 0; i < 4; i++) {
let sHat = sepAxes[i];
let centerDis = Math.abs(t.dot(sHat));
let dA = obbA.size[0] * Math.abs(obbA.axes[0].dot(sHat)) +
obbA.size[1] * Math.abs(obbA.axes[1].dot(sHat));
let dB = obbB.size[0] * Math.abs(obbB.axes[0].dot(sHat)) +
obbB.size[1] * Math.abs(obbB.axes[1].dot(sHat));
if (centerDis > dA + dB)
return false; // NOT intersect
}
return true; // intersect
}
}
init();
animate();
function init() {
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x888888);
document.body.appendChild(renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.OrthographicCamera(-20, 20, 20, -20, -10, 100);
camera.position.z = 10;
window.addEventListener('resize', onWindowResize, false);
keyboard = new KeyboardState();
...