feat: handle snap function added
This commit is contained in:
parent
2a669f6337
commit
2ff2f850f3
|
@ -0,0 +1,65 @@
|
|||
import { useEffect } from "react";
|
||||
import { detectModifierKeys } from "./shortcutkeys/detectModifierKeys";
|
||||
|
||||
// Define the props expected by the component
|
||||
type SnapControlsProps = {
|
||||
x_point: number; // X-coordinate value to snap
|
||||
z_point: number; // Z-coordinate value to snap
|
||||
};
|
||||
|
||||
const SnapControls: React.FC<SnapControlsProps> = ({ x_point, z_point }) => {
|
||||
useEffect(() => {
|
||||
// Handler function for keypress events
|
||||
const handleKeyPress = (event: KeyboardEvent) => {
|
||||
// Detect which modifier keys (Ctrl, Shift, etc.) are currently pressed
|
||||
const keyCombination = detectModifierKeys(event);
|
||||
|
||||
// Define the snapping distances
|
||||
const CTRL_DISTANCE = 1; // Coarse snapping when Ctrl is pressed
|
||||
const SHIFT_DISTANCE = 0.01; // Fine snapping when Shift is pressed
|
||||
|
||||
// Prevent default behavior to avoid unintended side effects
|
||||
event.preventDefault();
|
||||
|
||||
// Create new coordinates to apply snapping to
|
||||
let newX = x_point;
|
||||
let newZ = z_point;
|
||||
|
||||
// Check for modifier key combinations and apply appropriate snapping logic
|
||||
if (keyCombination) {
|
||||
if (keyCombination === "Ctrl") {
|
||||
// Snap to nearest integer unit
|
||||
newX = Math.round(x_point / CTRL_DISTANCE) * CTRL_DISTANCE;
|
||||
newZ = Math.round(z_point / CTRL_DISTANCE) * CTRL_DISTANCE;
|
||||
return { newX, newZ };
|
||||
}
|
||||
|
||||
if (keyCombination === "Ctrl+Shift") {
|
||||
// Snap to nearest small unit (0.01)
|
||||
newX = Math.round(x_point / SHIFT_DISTANCE) * SHIFT_DISTANCE;
|
||||
newZ = Math.round(z_point / SHIFT_DISTANCE) * SHIFT_DISTANCE;
|
||||
return { newX, newZ };
|
||||
}
|
||||
|
||||
if (keyCombination === "Shift") {
|
||||
// Incorrect snapping logic — rounding the point and multiplying by small value
|
||||
newX = Math.round(x_point) * SHIFT_DISTANCE;
|
||||
newZ = Math.round(z_point) * SHIFT_DISTANCE;
|
||||
return { newX, newZ };
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Attach keydown event listener when the component mounts
|
||||
window.addEventListener("keydown", handleKeyPress);
|
||||
|
||||
// Clean up the event listener when the component unmounts
|
||||
return () => {
|
||||
window.removeEventListener("keydown", handleKeyPress);
|
||||
};
|
||||
}, []); // Empty dependency array means this effect runs once on mount
|
||||
|
||||
return null; // This component doesn’t render anything
|
||||
};
|
||||
|
||||
export default SnapControls;
|
Loading…
Reference in New Issue