Rotating earth on its axis - javascript

I am trying to rotate earth about it's tilted axis in three js. I found this solution, and I am trying to use it on my code, but it doesn't do anything.
When I execute this code the planet just sits there and doesn't rotate at all. I don't really have a firm grasp of what a quaternion is or how it works, so I am not sure what is going wrong.
function rotateAroundAxis(object, axis, radians) {
var vector = axis.normalize();
var quaternion = new THREE.Quaternion().setFromAxisAngle(vector, radians);
object.rotation = new THREE.Euler().setFromQuaternion( quaternion );
}
earthAxis = new THREE.Vector3(Math.cos(23.4*Math.PI/180), Math.sin(23.4*Math.PI/180), 0);
function render() {
stats.update();
step += 0.02;
rotateAroundAxis(earth, earthAxis, step);
}

First, you need to tilt your sphere's geometry by 23.4 degrees by applying a transformation to it.
var radians = 23.4 * Math.PI / 180; // tilt in radians
mesh.geometry.applyMatrix( new THREE.Matrix4().makeRotationZ( - radians ) );
Then, to rotate your earth on its axis in object space, first normalize the axis you are rotating around.
earthAxis = new THREE.Vector3( Math.sin( radians ), Math.cos( radians ), 0 ).normalize();
Then in your render function, do this:
earth.rotateOnAxis( earthAxis, 0.01 ); // axis must be normalized
three.js r.69

Related

Ammo.js Three.js - Calculate force vector needed to make a basketball shot

I’m building a basketball game with three.js and ammo.js. (Enable3d)
The hoop/rim and ball’s positions are constantly changing (AR) so the shots will have to be dynamic and relative.
I need to calculate the force vector to apply to the ball, for a successful shot. In the game play the user will swipe to shoot and this will effect the “perfect shot” force.
I’ve seen many examples of code and equations for calculations of trajectories, ballistics, etc, and I’ve been converting them to JavaScript from C# as a lot of the scripts I’m finding are on the Unity forums.
I need a function that calculates the initial force vector3 To apply to the ball using the position of the ball, position of the hoop, the ball’s mass, and gravity. The initial angle or max height (terminal velocity y) will also have to be passed to this function, as I’ve noticed in all the equations and calculators I’ve seen.
EDIT:
So I converted a script I found on the Unity forums (Below), to Javascript/Three.js:
function getBallVelocity( ballPos, rimPos, angleDegrees, gravity ) {
const Vector3 = {
forward: new THREE.Vector3( 0, 0, 1 ),
up: new THREE.Vector3( 0, 1, 0 )
};
// Get angle in radians, from angleDegrees argument
const angle = THREE.Math.degToRad( angleDegrees );
gravity = gravity || 9.81;
// Positions of this object and the target on the same plane
const planarRimPos = new THREE.Vector3( rimPos.x, 0, rimPos.z ),
planarBallPos = new THREE.Vector3( ballPos.x, 0, ballPos.z );
// Planar distance between objects
const distance = planarRimPos.distanceTo( planarBallPos );
// Distance along the y axis between objects
const yOffset = rimPos.y - ballPos.y;
// Calculate velocity
const initialVelocity = ( 1 / Math.cos( angle ) ) * Math.sqrt( ( 0.5 * gravity * Math.pow( distance, 2 ) ) / ( distance * Math.tan( angle ) + yOffset ) ),
velocity = new THREE.Quaternion( 0, initialVelocity * Math.sin( angle ), initialVelocity * Math.cos( angle ) );
// Rotate our velocity to match the direction between the two objects
const planarPosDifferenceBetweenObjects = planarRimPos.sub( planarBallPos ),
angleBetweenObjects = Vector3.forward.angleTo( planarPosDifferenceBetweenObjects ),
angleUpRotated = new THREE.Quaternion().setFromAxisAngle( Vector3.up, angleBetweenObjects ),
finalVelocity = angleUpRotated.multiply( velocity );
return finalVelocity;
}
I'm calling the shot like this:
const velocity = getBallVelocity( ball.position, rim.position, 45 );
ball.body.applyForce( velocity.x, velocity.y, velocity.z )
It's shoots the wrong direction and very weak. I assume I'm not doing the rotation correctly at the end of the function, and the weakness could be due to not having mass multiplied. The ball's mass it 2, so I assume I should be multiplying some Y values by 2?? Have no idea :(
Here is the C# script I attempted a conversion of:
using UnityEngine;
using System.Collections;
public class ProjectileFire : MonoBehaviour {
[SerializeField]
Transform target;
[SerializeField]
float initialAngle;
void Start () {
var rigid = GetComponent<Rigidbody>();
Vector3 p = target.position;
float gravity = Physics.gravity.magnitude;
// Selected angle in radians
float angle = initialAngle * Mathf.Deg2Rad;
// Positions of this object and the target on the same plane
Vector3 planarTarget = new Vector3(p.x, 0, p.z);
Vector3 planarPostion = new Vector3(transform.position.x, 0, transform.position.z);
// Planar distance between objects
float distance = Vector3.Distance(planarTarget, planarPostion);
// Distance along the y axis between objects
float yOffset = transform.position.y - p.y;
float initialVelocity = (1 / Mathf.Cos(angle)) * Mathf.Sqrt((0.5f * gravity * Mathf.Pow(distance, 2)) / (distance * Mathf.Tan(angle) + yOffset));
Vector3 velocity = new Vector3(0, initialVelocity * Mathf.Sin(angle), initialVelocity * Mathf.Cos(angle));
// Rotate our velocity to match the direction between the two objects
float angleBetweenObjects = Vector3.Angle(Vector3.forward, planarTarget - planarPostion);
Vector3 finalVelocity = Quaternion.AngleAxis(angleBetweenObjects, Vector3.up) * velocity;
// Fire!
rigid.velocity = finalVelocity;
// Alternative way:
// rigid.AddForce(finalVelocity * rigid.mass, ForceMode.Impulse);
}
}
Thanks!
OK, three things:
The rotation of the velocity wasn't working. Used atan2 instead.
I needed to switch the subtracting Y axes points getting the yOffset
I needed to use .setVelocity(x, y, z) instead of .applyForce(x, y, z)
Here is the final script, hope it helps someone!
static getBallVelocity( ballPos, rimPos, angleDegrees, gravity ){
// Get angle in radians, from angleDegrees argument
const angle = THREE.Math.degToRad( angleDegrees );
gravity = gravity || 9.81;
// Positions of this object and the target on the same plane
const planarRimPos = new THREE.Vector3( rimPos.x, 0, rimPos.z ),
planarBallPos = new THREE.Vector3( ballPos.x, 0, ballPos.z );
// Planar distance between objects
const distance = planarRimPos.distanceTo( planarBallPos );
// Distance along the y axis between objects
const yOffset = ballPos.y - rimPos.y;
// Calculate velocity
const initialVelocity = ( 1 / Math.cos( angle ) ) * Math.sqrt( ( 0.5 * gravity * Math.pow( distance, 2 ) ) / ( distance * Math.tan( angle ) + yOffset ) ),
velocity = new THREE.Vector3( 0, initialVelocity * Math.sin( angle ), initialVelocity * Math.cos( angle ) );
// Rotate our velocity to match the direction between the two objects
const dy = planarRimPos.x - planarBallPos.x,
dx = planarRimPos.z - planarBallPos.z,
theta = Math.atan2( dy, dx ),
finalVelocity = velocity.applyAxisAngle( PopAShotAR.Vector3.up, theta )
return finalVelocity;
}

Translating camera with radius/diameter instead of x,y,z?

So I have this example as shown below and I was wondering if its possible to translate a camera by changing the radius & diameter instead of using x,y,z positions (Vector). For now im using a cube but I want to add a second camera basically.
Since I know where 0,0,0 (origin) is, is there any way to translate the cube by setting diameter radius or whatever is required and also lock it on the origin?
What I use to move the Cube (Three.js)
var posX,posY,posZ;
var scene, camera, render;
var cubeMesh,cube_Geometry, cube_Material;
class myWorld{
/* ... Setup World ... */
//excecute cube();
/* ... Set/Get positions (xyz) ... */
cube(){
cube_Geometry = new THREE.BoxGeometry(20, 20, 20);
cube_Material = new THREE.MeshNormalMaterial();
cube_Mesh = new THREE.Mesh(cube_Geometry, cube_Material);
cube_Mesh.position.set(0, 100, 100);
scene.add(cube_Mesh);
}
animate(){ //loop function
//THREE.Mesh.position.set (Three.js)
cube_Mesh.position.set(posX, posY, posZ);
}
}
What I want to achieve:
Use Spherical and setFromSpherical:
var r = 10;
var theta = 310 * (Math.PI / 180); /// 310 degree to radians
var sphericalPos = new THREE.Spherical(r, 0, theta);
cube_Mesh.position.setFromSpherical(sphericalPos);
// or just do cube_Mesh.position.setFromSphericalCoords(radius, phi, theta)
Spherical(radius: Float, phi: Float, theta : Float)
radius - the radius, or the Euclidean distance (straight-line distance) from the point to the origin. Default is 1.0.
phi - polar angle from the y (up) axis. Default is 0.
theta - equator angle around the y (up) axis. Default is 0.
The poles (phi) are at the positive and negative y axis. The equator (theta) starts at positive z.

start camera rotation from specific point in three js

I have a panoramic image loaded in threejs but it starts camera rotation from the logic below which is default in threejs
if ( isUserInteracting === false ) {
lon += 0.1;
}
lat = Math.max( - 85, Math.min( 85, lat ) );
phi = THREE.Math.degToRad( 90 - lat );
theta = THREE.Math.degToRad( lon );
camera.target.x = 100 * Math.sin( phi ) * Math.cos( theta );
camera.target.y = 100 * Math.cos( phi );
camera.target.z = 100 * Math.sin( phi ) * Math.sin( theta );
What I want to do is place the camera at a specific point which I am able to place using
camera.lookAt( -56.86954186163314, 0, -71.49481268065709 );
Now i want to start normal camera rotation from the above lookAt point. What I am currently doing is
camera.lookAt( -56.86954186163314 + camera.target.x, 0, -71.49481268065709 + camera.target.z);
Which is wrong I think.. PS (I am very weak in geometry, sin, cos).. Can any 1 please help me with this?? PS(I dont want to change camera.target.y It should be 0).. Thanks in advance..
This is best looked at from the perspective of vectors.
Take your lookAt position: that's a vector. You can make that vector spin around an axis using Vector3.applyAxisAngle. As you update the vector, make your camera look at it.
For your example, you want the camera to look at -56.86954186163314, 0, -71.49481268065709, and then spin 360° about the Y-axis (the camera position doesn't change, and the lookAt target doesn't change its Y value).
var lookVector = new THREE.Vector3();
// later...
lookVector.set(x, y, z); // -56.86954186163314, 0, -71.49481268065709
// down with your render function...
var axis = new THREE.Vector3(0, 1, 0);
function render(){
lookVector.applyAxisAngle(axis, 0.001); // or some other theta
camera.lookAt(lookVector);
renderer.render(scene, camera);
}
You'll need to track when your thetas add up to 360°, and perform logic to stop the rotation, but I'll leave that as an exercise for you.

How to rotate a THREE.PerspectiveCamera around on object

I am making this program where you can click on an object, zoom to it, then look at it from all angles by holding the right mouse button and dragging. I need the camera to be going around the object, not rotate the object with the camera looking at it. I honestly just have no idea how to math it out!
For testing there is already a game object with an xyz we have selected and are looking at
var g = new GameObject(500, 0, 0);//The game object with xyz
this.selected = g;//set selected to g
//Create and set the camera
this.camera = new THREE.PerspectiveCamera(45, w/h, 1, 10000);
this.camera.position.x = 0;
this.camera.position.y = 0;
this.camera.position.z = 0;
//set camera to look at the object which is 500 away in the x direction
this.camera.lookAt(new THREE.Vector3(this.selected.x, this.selected.y, this.selected.z));
So the radius between the camera and the object is 500 and while selected and rotating, the camera should always be 500 away.
I update the scene here:
Main.prototype.update = function(){
this.renderer.render(this.scene, this.camera);//scene is just some ambient lighting
//what to do when mouse right is held down
if(this.rightMouseDown){
//placeholder functionality, needs to rotate around object based on mouse movements
this.camera.position.x -= 5;
}
}
How do I rotate this camera around g with a radius of 500?!?!
As gaitat mentioned, trackball controls are the best place to start with many configurable parameters to make camera rotation/revolution easy. One enormous potential benefit of this method ( especially for your project ) is avoiding "gimbal lock" which is the source of much frustration when working with rotations. Here's a link that might help you with Trackball controls and Orbitcontrols:
Rotate camera in Three.js with mouse
Another option would be setting camera coordinates yourself in the animation loop which is actually quite simple:
var angle = 0;
var radius = 500;
function animate() {
...
// Use Math.cos and Math.sin to set camera X and Z values based on angle.
camera.position.x = radius * Math.cos( angle );
camera.position.z = radius * Math.sin( angle );
angle += 0.01;
...
}
Another option would be to connect the camera to a pivot object and just rotate the pivot:
var camera_pivot = new THREE.Object3D()
var Y_AXIS = new THREE.Vector3( 0, 1, 0 );
scene.add( camera_pivot );
camera_pivot.add( camera );
camera.position.set( 500, 0, 0 );
camera.lookAt( camera_pivot.position );
...
camera_pivot.rotateOnAxis( Y_AXIS, 0.01 ); // radians
If you pursue this option, be aware that the camera object is in "camera pivot space", and might be more challenging to manipulate further.

How to rotate a Three.js Vector3 around another Vector3?

Here I want to rotate 'endpoint' vector around 'startpoint' vector.
This rotates endpoint vector around world's z-axis:
endpoint.copy(new THREE.Vector3(startpoint.x,startpoint.y,startpoint.z));
endpoint.add(new THREE.Vector3(0, scale, 0 ));
var matrix = new THREE.Matrix4().makeRotationAxis( axis_z, angle );
endpoint.applyMatrix4( matrix );
I have tried to save vector's translation to temporary matrix, and after applying rotation, restore translation back to endpoint vector:
endpoint.copy(new THREE.Vector3(startpoint.x,startpoint.y,startpoint.z));
endpoint.add(new THREE.Vector3(0, scale, 0 ));
var translateMatrix = new THREE.Matrix4().makeTranslation(endpoint.x, endpoint.y, endpoint.z);
var translation = new THREE.Matrix4().copyPosition(translateMatrix);
translateMatrix.makeRotationAxis(axis_z, angle);
translateMatrix.copyPosition(translation);
endpoint.applyMatrix4(translateMatrix);
This code works for rotations, but all the translations are wrong.
Is there an easy way for vector rotation relative to another vector?
UPD. Resolved this. I was blind. No need for translations. What I had to do: apply rotation to vectors delta (endpoint - startpoint), and in the end, add the rotated delta to startpoint (startpoint + delta):
var vector_delta = new THREE.Vector3().subVectors(endpoint, startpoint);
vector_delta.applyAxisAngle( axis_z, rota );
endpoint.addVectors(startpoint, vector_delta);

Categories

Resources