Sounak Garai
Sounak Garai

Reputation: 15

How can I achieve accuracy of raycaster while mouse hover on different pieces of a LineSegment?

I have created one example to draw a LineSegment in three.js. I have applied vertexColors to its material and pushed color for vertices. Now when I hover on all the different pieces of the LineSegment I change the color of that vertex (along with the next or previous vertex depending on the order it got pushed in the geometry.vertices array so that a line gets its color changed, you will understand once you see the code) that gets picked by the raycaster.

The jsfiddle link is here. https://jsfiddle.net/sounakgarai/tedmc2f0/3/

Now the issue is that the hovering is not accurate; a piece of the Linesegment gets its color changed even when the mouse cursor is in a far distance from it (you will be able to see it when you run it). I would like to see the accuracy in this case. The piece of LineSegment should change the color when the mouse cursor is accurately on it.

Is this achievable?

Upvotes: 1

Views: 302

Answers (1)

prisoner849
prisoner849

Reputation: 17596

You don't take in count, that your container is not at the [0, 0] position on the screen.

As an option, you can use .getBoundingClientRect() method to get the bounding rect of your container and then subtract it from the mouse coordinates you get in your listener.

var rect;
. . .

// in the listener
rect = myDiv.getBoundingClientRect();

mouse.x = ((event.clientX - rect.left) / container.clientWidth) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / container.clientHeight) * 2 + 1;

jsfiddle example

PS Just for your information, interface of jsfiddle.net has the Tidy button, which makes the code well-formed and thus much more readable.

Upvotes: 1

Related Questions