I have a threejs mesh that I want to move from side to side when I move my mouse after clicking it.
On mousemove function here is my code.
The problem I'm running into is if I first move to the right and then I switch directions it doesn't start moving to the left until I get closer to my original x position where I clicked my mouse for the first time.
let originx;
onDocumentClick(evt) {
originx = evt.pageX;
document.addEventListener('mousemove', onMouseMove);
}
onMouseMove(evt) {
let _newX = myMesh.position.x + (originx - evt.pageX);
myMesh.position.set(_newX, myMesh.position.y, myMesh.position.z);
}
It's not quite clear the effect you're trying to achieve, so I'm going to take a stab in the dark... If you update your answer with a more precise description, let me know and I will update this answer.
I think the biggest problem with your logic is that you are basing everything on MouseEvent.pageX. This property's coordinate system starts at 0 on the left edge, and has a positive value on the right edge. As such, when you move your mouse anywhere to the right of your original click point, you will always have a MouseEvent.pageX that is larger than the MouseEvent.pageX of the original point, regardless of the direction in which you are moving your mouse. Likewise, pageX will only be smaller than the original click point's pageX value while your cursor is to the left of that click point.
I think the property you're actually looking for is MouseEvent.movementX. This property describes only the change in position since the last MouseEvent. It also takes direction into account, so a movement to the right will produce a positive value, and a movement to the left will produce a negative value.
Try replacing pageX with movementX and see if that gets you closer to what you want.