5
votes

I created a basic scene using three.js. My goal is to make a pov camera based on FirstPersonControls.js

I modified its code to fit my needs (moving view on mouse click, etc.) I m almost done but a bug remains: when I move the camera on the first time, it doesn't start moving from the object's position I m looking at on the scene load.

This only happens when I set a camera's position. Otherwise, it almost works, as you can see on this link: http://jsfiddle.net/42qeojs0/

Just uncomment these 3 lines (after line 60)

    camera.position.x = 10;
    camera.position.y = 10;
    camera.position.z = 250;

Then, try to move the view around the object by dragging your mouse. You'll see the start position of your drag isn't the same as the position where you first look at.

Thanks in advance

1

1 Answers

1
votes

To correct the initial jump around you get when you click the mouse. Introduce a new variable dist for the distance to the object your looking at and use atan2 as a more reliable way of getting the longitude.

dist = Math.hypot(blue1.position.x,blue1.position.y,blue1.position.z);
phi = Math.acos(blue1.position.y/dist);

theta = Math.atan2(blue1.position.z,blue1.position.x);

lon = THREE.Math.radToDeg(theta);
lat = 90-THREE.Math.radToDeg(phi);

In onDocumentMouseMove use

camera.target.x = dist * Math.sin( phi ) * Math.cos( theta );
camera.target.y = dist * Math.cos( phi );
camera.target.z = dist * Math.sin( phi ) * Math.sin( theta );

This way if you take the initial position, calculate lat, long and dist, and then calculate the looking at vector you get what you started with. Using a fixed multiple of 500 in effect made sudden jump to a position further away than you started. (Note Math.Hypot is not supported in IE so you might need the calculate this yourself if targeting IE).