DataTools3/input-controller.js

63 lines
1.5 KiB
JavaScript

let draggingBox = null;
let draggingCamera = false;
let lastMousePos = {x: 0, y: 0};
document.addEventListener("mousedown", (e) => {
let x = e.clientX;
let y = e.clientY;
if (e.button == 0) {
if (e.target.classList.contains("boxDeleteButton")) return;
for (let box of Box.instances) {
let topBarRect = box.element.getElementsByClassName("boxTopBar")[0].getBoundingClientRect();
box.element.classList.remove("dragging");
if (isPointInRect(x, y, topBarRect.x, topBarRect.y, topBarRect.width, topBarRect.height)) {
draggingBox = box;
box.element.classList.add("dragging");
break;
}
}
}
if (e.button == 1 || e.button == 2) {
draggingCamera = true;
e.preventDefault();
}
});
document.addEventListener("mouseup", (e) => {
if (e.button == 0 && draggingBox != null) {
draggingBox.element.classList.remove("dragging");
draggingBox = null;
}
if (e.button == 1 || e.button == 2) {
draggingCamera = false;
}
})
document.addEventListener("mousemove", (e) => {
let delta = {x : e.clientX - lastMousePos.x, y : e.clientY - lastMousePos.y};
if (draggingBox != null) {
draggingBox.x += delta.x;
draggingBox.y += delta.y;
draggingBox.updatePosition();
}
if (draggingCamera) {
Camera.x -= delta.x;
Camera.y -= delta.y;
Box.updateAllPositions();
document.getElementById("canvas").style.backgroundPosition = (-Camera.x) + "px " + (-Camera.y) + "px";
}
lastMousePos = {x: e.clientX, y: e.clientY};
})
function isPointInRect(px, py, rx, ry, rw, rh) {
return px >= rx && px <= rx + rw && py >= ry && py <= ry + rh;
}