To view the complete code, visit this Glitch project:
Within public/components.js
, I have defined a custom AFRAME component that enables rotation of an item when dragged with the mouse.
AFRAME.registerComponent('drag-rotate-component', {
schema: { speed: { default: 10 } },
init: function () {
this.ifMouseDown = false;
this.x_cord = 0;
this.y_cord = 0;
document.addEventListener('mousedown', this.OnDocumentMouseDown.bind(this));
document.addEventListener('mouseup', this.OnDocumentMouseUp.bind(this));
document.addEventListener('mousemove', this.OnDocumentMouseMove.bind(this));
},
// Records x and y coordinates of mouse position when mouse is clicked
OnDocumentMouseDown: function (event) {
this.ifMouseDown = true;
this.x_cord = event.clientX;
this.y_cord = event.clientY;
},
OnDocumentMouseUp: function () {
this.ifMouseDown = false;
// Saves rotation to localstorage
let rotation = this.el.object3D.rotation.z;
localStorage.setItem('angle', rotation);
},
OnDocumentMouseMove: function (event) {
if (this.ifMouseDown) {
// Calculates difference between current and previous mouse positions
var temp_x = event.clientX - this.x_cord;
var temp_y = event.clientY - this.y_cord;
this.el.object3D.rotation.z = temp_x * this.data.speed / 1000;
}
}
});
The code functions correctly in the browser.
However, when accessed from Chrome on my mobile phone or Surface Pro touch tablet, dragging my finger on the screen yields no result.
How can I make it work on touch devices?
I attempted the solution provided in this query Mouse events not working in mobile
Using event.touches[0].clientX
and event.touches[0].clientY
. But these return as undefined.