After browsing through various posts and documentation, I am trying to figure out how to make a BoxMesh follow the mouse cursor. My ultimate goal is to implement joystick touch controls for games like Heroes of Loot. For now, I am focusing on getting directional velocity to work correctly.
Here's what I have in my mouse down event:
if (scene.mouseControls.isDown) {
var coords = scene.mouseControls.screenCoords;
var vector = new THREE.Vector3();
vector.set(
( scene.mouseControls.screenCoords.x / window.innerWidth ) * 2 - 1,
0.5,
- ( scene.mouseControls.screenCoords.y / window.innerHeight ) * 2 + 1
);
vector.unproject(scene.camera);
var p1 = this.mesh.position;
var p2 = vector;
var angle = Math.atan2(p2.x - p1.x, p2.z - p1.z);
var velX = Math.sin(angle) * 20;
var velZ = Math.cos(angle) * 20;
console.log(vector.x, vector.z);
this.mesh.setLinearVelocity(new THREE.Vector3(velX, 0, velZ));
}
else {
this.mesh.setLinearVelocity(notMovingVector);
}
However, the calculated velocity seems to oscillate back and forth, resulting in jittery player movement.
This is how I set the mouse coordinates:
window.addEventListener(activeEventList[POINTER_MOVE], function (e) {
if (e.touches) {
var t = e.touches[0];
_this.screenCoords.x = t.clientX;
_this.screenCoords.y = t.clientY;
}
else {
_this.screenCoords.x = e.clientX;
_this.screenCoords.y = e.clientY;
}
});
I am not considering scroll offset since the scene covers the entire screen.
Edit
I have removed the previous direction code and instead used atan2 to calculate an angle and apply it, similar to how I've done it in 2D games.