Projecting points along the surface on a sphere into 2D - javascript

I have a number of objects that I am rendering in HTML/CSS/JavaScript. The objects all sit on the surface of an invisible sphere with radius R.
Additionally, the interaction with the user allows this invisible sphere to be rotated arbitrarily.
The obvious solution is spherical co-ordinates assigned to the objects (Theta, Phi, and fixed Radius), which is the converted to Cartesian 3D co-ordinates, and then I can either just drop the depth (Z), or apply some fancy perspective. I will worry about perspective later...
Since I'm working with graphics, X/Y is horizontal/vertical respectively, and Z is depth where +ve is sticking out of the screen and -ve is inside the monitor.
I have a JavaScript array of objects called objects[], each of which has a Theta and Phi. I assume that Theta is rotation about the Y axis, and Phi is rotation about the X axis, such that at Phi = 0 and Theta = 0, we are at (X,Y,Z) = (0,0,R);
Since I'm rotating the invisible sphere, I don't want to have to change the Theta and Phi of each individual objects, which would also just add to numerical instability. Instead, I store a global Theta and Phi which is associated with the rotation of the sphere itself.
Hence, the "effective" Theta and Phi of the points are the Theta and Phi of the points plus the global Theta and Phi.
According to Wikipedia, WolframAlpha, MathWorld, and many other resources, we can find the Cartesian co-ordinates from spherical co-ordinates in the following way:
z = r * sin(phi) * cos(theta);
y = r * sin(phi) * sin(theta);
x = r * cos(phi);
(I've swapped Theta and Phi from Wikipedia as I'm using them backwards, and my X/Y/Z co-ordinates are different too).
I'm not sure why, but when I render these objects they don't look right at all. If you imagine a point on the equator of a sphere with Theta = Pi/4, and you rotate the sphere about the Y axis, the point should only move up and down if projected onto 2D and no perspective transformations are used. However, this isn't at all what happens. The points move from the right to the left side of the screen. The whole thing looks all wrong.

Order matters. When you use your equations
z = r * sin(phi) * cos(theta);
y = r * sin(phi) * sin(theta);
x = r * cos(phi);
then you can interpret them as a rotation first by phi about y and second by theta about x (for appropriate choices of angle measurement directions):
(x1, y1, z1) = (r, 0, 0)
(x2, y2, z2) = (x1 * cos(phi) - z1 * sin(phi),
y1,
x1 * sin(phi) + z1 * cos(phi))
= (r * cos(phi), 0, r * sin(phi))
(x3, y3, z3) = (x2,
y2 * cos(-theta) - z2 * sin(-theta),
y2 * sin(-theta) + z2 * cos(-theta))
= (r * cos(phi),
r * sin(phi) * sin(theta),
r * sin(phi) * cos(theta))
When you simply add those angles, you end up with a wrong order: rotating first by phi1then by theta1 then by phi2 and then by theta2 about the different axes is not the same as rotating by phi1 + phi2 first and theta1 + theta2 afterwards. You're changing the order between theta1 and phi2, which breaks your 3D position.
Better use rotation matrices, quaternions, a library (like three.js) which encapsulates this for you, or make sure you properly combine euler angles.

Related

Calculate angle change after hitting a tilted wall

I'm making a game in javascript, where an object is supposed to bounce from walls. I really tried to get it to work myself, but it never works correctly.
Let's say theres a ball bouncing inside this cage (blue = 30°, brown = 60°);
The ball's coordinates are known. The angle of movement is known. The point of collision (P) coordinates are known. The angle of the wall is known. The ball's position is updating it's coordinates inside a setInterval function using this function:
function findNewPoint(x, y, angle, distance) {
var result = {};
result.x =(Math.cos(angle * Math.PI / 180) * distance + x);
result.y = (Math.sin(angle * Math.PI / 180) * distance + y);
return result;
So, upon colliding, there should be a function that properly changes the ball's angle. It's a very complicated problem it seems, because even if I know that the wall is 30°, its important to know from what side the ball is colliding into it. I tried using the "Reflection across a line in the plane" formula and also some vectors, but it never worked out for me. I'm not expecting a complete answer with code, if someone could suggest in what way this should be programmed, it would help aswell.
Edit:
Thanks for your tips guys, I realized what was causing the most confustion; if I select an angle on the canvas with my mouse, the starting coordinate(0,0) is in the bottom left corner. But since the canvas' starting coordinate is in the top left corner, this has to be considered.
Basically using this formula for calculating the angle:
function angle(cx, cy, ex, ey) {
var dy = ey - cy;
var dx = ex - cx;
var theta = Math.atan2(dy, dx);
theta *= 180 / Math.PI;
return theta;
}
if the ball moved from (50,50) to (100,100), the angle would be -45.
Now, this angle changes in the following way when hitting walls:
If im honest, I got these out of trial and error, am not really understanding why exactly 60 and 120.
It is not wise to use angle for moving ball and calculate Cos/Sin again and again. Instead use unit velocity direction vector with components vx, vy like this:
new_x = old_x + vx * Velocity_Magnitude * Time_Interval
Note that vx = Cos(angle), vy = Sin(angle), but with direction approach you seldom need to use trigonometric functions.
Tilted wall with angle Fi has normal
nx = -Sin(Fi)
ny = Cos(Fi)
To find reflection , you need to calculate dot product of velocity and normal
dot = vx * nx + vy * ny
Velocity after reflection transforms:
vnewx = v.x - 2 * dot * n.x
vnewy = v.y - 2 * dot * n.y
Use these values for further moving
(note that you can use both internal and external normal direction, because direction flip changes both components, and sign of 2 * dot * n.x remains the same)
Examples:
horizontal moving right
vx=1, vy=0
30 degrees wall has normal
nx=-1/2, ny=Sqrt(3)/2
dot = -1/2
vnewx = 1 - 2 * (-1/2) * (-1/2) = 1/2
vnewy = 0 - 2 * (-1/2) * Sqrt(3)/2 = Sqrt(3)/2
(velocity direction angle becomes 60 degrees)
horizontal moving left
vx=-1, vy=0
330 degrees wall (left bottom corner) has normal
nx=1/2, ny=Sqrt(3)/2
dot = -1/2
vnewx = -1 - 2 * (-1/2) * (1/2) = -1/2
vnewy = 0 - 2 * (-1/2) * (Sqrt(3)/2) = Sqrt(3)/2
(velocity direction angle becomes 120 degrees)
Here is a function that returns the angle of reflection given an angle of incidence and a surface angle (in degrees). It also ensures that the returned angle is between 0 and 359 degrees.
function angleReflect(incidenceAngle, surfaceAngle){
var a = surfaceAngle * 2 - incidenceAngle;
return a >= 360 ? a - 360 : a < 0 ? a + 360 : a;
}
Here's a demonstration, where the blue line is the angle of incidence, the purple line is the angle of reflection, and the black line is the surface.
If you're assuming that the ball behaves like light bouncing off a mirror, then the angle of incidence equals the angle of reflection.
So your board is 30° from 0° (straight up). The means the normal (perpendicular to the board at the point the ball hits ) is 300°. Say the ball arrives from 280°, it must leave at 320° as the difference between the angle of incidence and the normal and the angle of reflection and the normal must be equal.

Find four coordinates of the rectangle after the rotation and translation

I need to adapt the algorithm (or find the formula) to work in all three dimensions to find the new four coordinates. In the example i've obtained the new width and height of a transformed (rotate and perspective), but i don't know how to extract the angle and the new coordinates.
var x = Math.cos(angle) * origy;
var z = Math.sin(angle) * origy;
return x * p / (p + z);

How to generate coordinates to represent a circle in 3D programming?

Lets say I have 10 objects. The first object is placed at x75, y0, z0. Now lets say I wanted to orient the objects so they form a circle with x0, y0, z0 at it's center. And each object is an equal distance from each other. Is there a formula I can use to generate the coordinates? I should mention the number of objects wont always be 10. It's a variable so some times it might be 15 or 20 or any other number.
You can use some formula like:
x = x0 + r * cos(theta * pi / 180);
y = y0 + r * sin(theta * pi / 180);
so x0 = 0 and y0 = 0.
For theta, it will be the degree, which depends on the number of objects. So if you have 10 objects, theta will be a multiple of 36. So basically it is a multiple of 360/num of objects.
r is the radius of the circle, so if the first one is at (75, 0, 0), then r = 75.

Drawing a custom number of straight lines across 1 point with javascript

I'm trying to develop a small application using html5 and canvas/KineticJS. I'd like to trace a number of rays that start from a 2d point to infinite, just setting a custom angle degree. For example, if I set 90° the app should render four rays (two straight lines, one vertical and one horizontal that meet in my 2d point). If I set 60° I should see 3 straight lines, like an asterisk *
The longest line you'll ever have to draw is the size of the canvas's diagonal:
var r = Math.sqrt(Math.pow(canvas.width, 2) + Math.pow(canvas.height, 2));
Use sin and cos to calculate each of your end points at that radius:
var theta = delta * Math.PI / 180.0;
var dx = r * Math.cos(n * theta);
var dy = r * Math.sin(n * theta);
Then, just draw lines from (x, y) to (x + dx, y + dy). Simples.

Points on a (un)rotated rectangle

I found this excellent question and answer which starts with x/y (plus the center x/y and degrees/radians) and calculates the rotated-to x'/y'. This calculation works perfectly, but I would like to run it in the opposite direction; starting with x'/y' and degrees/radians, I would like to calculate the originating x/y and the center x/y.
(x', y') = new position
(xc, yc) = center point things rotate around
(x, y) = initial point
theta = counterclockwise rotation in radians (radians = degrees * Pi / 180)
dx = x - xc
dy = y - yc
x' = xc + dx cos(theta) - dy sin(theta)
y' = yc + dx sin(theta) + dy cos(theta)
Or, in JavaScript/jQuery:
XYRotatesTo = function($element, iDegrees, iX, iY, iCenterXPercent, iCenterYPercent) {
var oPos = $element.position(),
iCenterX = ($element.outerWidth() * iCenterXPercent / 100),
iCenterY = ($element.outerHeight() * iCenterYPercent / 100),
iRadians = (iDegrees * Math.PI / 180),
iDX = (oPos.left - iCenterX),
iDY = (oPos.top - iCenterY)
;
return {
x: iCenterX + (iDX * Math.cos(iRadians)) - (iDY * Math.sin(iRadians)),
y: iCenterY + (iDX * Math.sin(iRadians)) + (iDY * Math.cos(iRadians))
};
};
The math/code above solves for the situation in Figure A; it calculates the position of the destination x'/y' (green circle) based on the known values for x/y (red circle), the center x/y (blue star) and the degrees/radians.
But I need math/code to solve for Figure B; where I can find not only the destination x/y (green circle), but also the destination center x/y (green star) from the known values of the starting x/y (grey circle, though probably not needed), the destination x'/y' (red circle) and the degrees/radians.
The code above will solve for the destination x/y (green circle) via iDegrees * -1 (thanks to #andrew cooke's answer which has since been removed by him), but in order to do that I need to feed into it the location of the destination center x/y (green star), and that is the calculations I'm currently missing, as you can see in Diagram C, below:
So... how do I find the coordinates ?/? (green star) given n, A (angle) and x'/y' (red circle)?
You're trying to find an inverse transformation. You start with the composition of two linear transformations, a translation T and a rotation R. You apply R first to a vector x and T second, so the expression is y = TRx. To solve the inverse problem you need the inverse of TR, written (TR)-1, which is equal to R-1T-1. The inverse of the rotation R is just the rotation by the negative of the angle (which you mention). The inverse of the translation is, similarly, the original translation multiplied by -1. So your answer is x = R-1T-1y.
In your present situation, you're given the rotation by means of its angle, but you'll need to compute the translation. You'll need the grey circle, which you didn't think you would need. Apply the rotation R (not its inverse) to the gray circle. Subtract this point from the red circle. This is the original translation T. Reverse the sign to get T-1.

Categories

Resources