I'd like to limit rotation of an object, so I've written following snippet:
if (targetRotation < constraintMin) {
targetRotation = constraintMin;
} else if (targetRotation > constraintMax) {
targetRotation = constraintMax;
}
It works fine when moving in clockwise direction (big chunk starting right of blue lines), however nothing I've tried works work counterclockwise (smaller chunk between blue lines) because of Math.PI
-> -Math.PI
jump.
Here's working outer angle constraint between -3 and 3. However I'd like to make one between 3 and -3, but cannot think of how to do that.
const SPEED = 0.05;
let div = document.querySelector('div');
let targetRotation = Math.PI - 0.1;
let rotation = 0;
const CONSTRAINT_MIN = -3;
const CONSTRAINT_MAX = 3;
function rotate(dt) {
let deltaRotation = (targetRotation - rotation) % (Math.PI * 2);
let constraintDiffMin = ((CONSTRAINT_MIN - deltaRotation) + Math.PI * 4) % (Math.PI * 2);
let constraintDiffMax = ((CONSTRAINT_MAX - deltaRotation) + Math.PI * 4) % (Math.PI * 2);
//This works for outer angle
if (deltaRotation < CONSTRAINT_MIN) {
deltaRotation = CONSTRAINT_MIN;
} else if (deltaRotation > CONSTRAINT_MAX) {
deltaRotation = CONSTRAINT_MAX;
}
//But how to make it constraint inner angle between MAX and MIN?
if (Math.abs(deltaRotation) > Math.PI) {
deltaRotation -= 2 * Math.PI * (deltaRotation / Math.abs(deltaRotation));
}
rotation += deltaRotation * SPEED;
div.style.transform = 'rotate(' + rotation + 'rad)';
requestAnimationFrame(rotate);
}
document.addEventListener('mousemove', function(e) {
targetRotation = Math.atan2(e.y - 100, e.x - 100);
}, false);
requestAnimationFrame(rotate);
div {
width: 100px;
height: 30px;
background: linear-gradient(45deg, #BADA55, red);
transform: rotate(0);
margin: 85px 50px 0;
}
<div>
</div>
How can I resolve this?