Jamie Fearon
Jamie Fearon

Reputation: 2634

Getting coordinates of the mouse in relation to 3D space in THREE.js

I have struggled for the past 3 weeks trying to figure this out. If anyone could help me I would appreciate it so much.

I'm developing a game similar to Geometry Wars in where I have a triangle in the middle of the screen which you can move around.

The problem is I need the triangle to rotate and face toward the direction of the mouse curser. I don't need to worry about the z-axis per-say as I always have the camera in a fixed position (z=500) and I am treating the scene as a "2D scene" - all the action occurs on the z=0 plane.

Calculating the angle between the triangle and the mouse is elementary:

targetAngle = Math.atan2(mouseCoord.y-this.position.y, mouseCoord.x-this.position.x)

where this is the mesh.

The problem is that the mouseCoords are in standed Dom window format whilst the position of the triangle is in Three.js format.

Q) How would I convert the mouse coords to represent the coords on the z=0 plane where the triangle is?

I have tryed so many ways including ray intersection but nothing works ;(

Thank you all for your help and thank you so much for an amazing framework!!!!

Upvotes: 7

Views: 10566

Answers (2)

cubicleDowns
cubicleDowns

Reputation: 121

I suspect your intersection isn't working because of a CSS offset by your canvas within the DOM.

If you need the triangle to look at something specific, you should simply be able to use the "lookAt" method of the triangle.

To have it look at the camera for example: triangleMesh.lookAt(camera.position);

Upvotes: -5

lesolorzanov
lesolorzanov

Reputation: 3556

I don't actually see the problem. use the THREE.vector3 with the z coord in 0. then use something like triangle.rotate(THREE.vector3(targetAngle,0,0) or something

Upvotes: 0

Related Questions