If you want to navigate a car along a curved path while following its direction:
- Start by outlining the key points of a spline
- Create the spline based on these defined points
- Increment a value representing the car's position on the curve, ranging from the starting point (0) to the endpoint (1)
Ensure the car is oriented towards a point slightly ahead.
//1. Define the spline's pivotal points
var points = [
new THREE.Vector3( x1, y1, z1 ),
new THREE.Vector3( x2, y2, z2 ),
...
new THREE.Vector3( xn, yn, zn )
];
//2. Generate the spline
var spline = new THREE.CatmullRomCurve3( points );
//Updated in r72. Previously: THREE.SplineCurve3
//3. Specify the car's position on the spline, between the start (0) and end (1)
var carPositionOnSpline = 0;
//In each increment (within your render loop or 'update' function of a tween), do the following:
var newPosition = spline.getPoint( carPositionOnSpline );
car.position.copy( newPosition );
//Adjust the car's orientation to face the road
var target = spline.getPoint( carPositionOnSpline + .001 );
car.lookAt( target );//+.001 or alternative value
To make the wheels rotate, calculate the cross product of the orientation vector with the previous orientation vector. Assuming movement along the x-z plane, the wheel's alignment will be proportional to the y-component of the resultant vector:
var actualOrientation = new THREE.Vector3().subVectors( target, newPosition );
actualOrientation.normalize();
var orientation=new THREE.Vector3().crossVectors( actualOrientation, previousOrientation );
wheel.rotation.y = something * orientation.y;
previousOrientation = actualOrientation;