[SOLVED] Raycaster on mouse click laggs an action behind

Hello,

I’m trying to get the intersection point of a mesh loaded through the FBXLoader on a mouseDown event, which works for the most part. But for some reason the rayCaster.intersectObjects seems to always be lagging behind a single mouseclick.

My problem can be viewed in this fiddle. As you can see in the console it’ll always log the data from the previous click, instead of the current.

I’m fairly sure the problem is somewhere on my end, so any help would be greatly appreciated!

Thank you for your time!
-Remy

This problem occurs when the canvas if not full screen. You can use the canvas bounds instead of the window width/height like so


  var canvasBounds = renderer.domElement.getBoundingClientRect();

  mouse.x = ( ( event.clientX - canvasBounds.left ) / ( canvasBounds.right - canvasBounds.left ) ) * 2 - 1;
  mouse.y = - ( ( event.clientY - canvasBounds.top ) / ( canvasBounds.bottom - canvasBounds.top) ) * 2 + 1;

  raycaster.setFromCamera( mouse, camera );

http://jsfiddle.net/rv41kzuy/38/

1 Like

It’s also important that raycaster.setFromCamera( mouse, camera ); is executed with the latest event data. So place it always right before raycaster.intersectObjects(). Since raycaster.setFromCamera() was placed in your render loop, you have seen the previous click in the console.

2 Likes

As always thanks for the quick and clear replies guys, you’re amazing.

Oops! Didn’t see that.

Also note that clientX/clientY can give you incorrect positions.

It’s also heavily dependent to which object you’re attaching your click event handlers. Unless you’re guaranteed to be running in a full window, attach your mousedown/mouseup events directly to the canvas, not window.

@TheJim01
Also discussed here :slight_smile:

1 Like

@prisoner849 I was looking for your post but couldn’t find it :smile:

@looeee
I remember, that you’ve replied with “even better” and found that thread by your reply, using “search” :smile: :beers:

1 Like

:laughing: :laughing: :laughing:

1 Like