yumedoll
Active Coder
I have this script I picked off of a codepen
What it does is it takes advantage of the dragging function to change an elements rotation.
The thing is, I'm making a baking game and I want to use this script for the knobs on the oven. I need them to snap to every 90° and limit the knobs rotation to no more than 360°.
From what I can observe by the script, the angle is calculated in radiants, so I'm assuming if I wanna do this I might need to divide
But I'm not entirely sure how to start going about the snapping part though. Anyone who's familiar with interact.js can help?
EDIT: I tried changing the rotation to degrees here, and it works like a charm! Still don't know about the snapping though.
JavaScript:
interact('.drag-rotate')
.draggable({
onstart: function (event) {
const element = event.target;
const rect = element.getBoundingClientRect();
// store the center as the element has css `transform-origin: center center`
element.dataset.centerX = rect.left + rect.width / 2;
element.dataset.centerY = rect.top + rect.height / 2;
// get the angle of the element when the drag starts
element.dataset.angle = getDragAngle(event);
},
onmove: function (event) {
var element = event.target;
var center = {
x: parseFloat(element.dataset.centerX) || 0,
y: parseFloat(element.dataset.centerY) || 0,
};
var angle = getDragAngle(event);
// update transform style on dragmove
element.style.transform = 'rotate(' + angle + 'rad' + ')';
},
onend: function (event) {
const element = event.target;
// save the angle on dragend
element.dataset.angle = getDragAngle(event);
},
})
function getDragAngle(event) {
var element = event.target;
var startAngle = parseFloat(element.dataset.angle) || 0;
var center = {
x: parseFloat(element.dataset.centerX) || 0,
y: parseFloat(element.dataset.centerY) || 0,
};
var angle = Math.atan2(center.y - event.clientY,
center.x - event.clientX);
return angle - startAngle;
}
The thing is, I'm making a baking game and I want to use this script for the knobs on the oven. I need them to snap to every 90° and limit the knobs rotation to no more than 360°.
From what I can observe by the script, the angle is calculated in radiants, so I'm assuming if I wanna do this I might need to divide
angle by pi and multiply by 180.But I'm not entirely sure how to start going about the snapping part though. Anyone who's familiar with interact.js can help?
EDIT: I tried changing the rotation to degrees here, and it works like a charm! Still don't know about the snapping though.
JavaScript:
onmove: function (event) {
var element = event.target;
var center = {
x: parseFloat(element.dataset.centerX) || 0,
y: parseFloat(element.dataset.centerY) || 0,
};
var angle = getDragAngle(event);
var angledeg = angle/Math.PI*180;
// update transform style on dragmove
element.style.transform = 'rotate(' + angledeg + 'deg' + ')';
}
Last edited: