Formula to Mimic 3D Distance in 2D Space? - javascript

I'm working on a simple 2D game, and am trying to mimic a 3D perspective (similar to many early games like Monkey Island). I've searched SO for awhile now and everything seems to be dealing with 3D. Does anyone happen to know the formula I would use to scale a DIV down as it moves up (away) from the camera?
Thanks!

In Monkey Island the backgrounds are 2D images with varying degrees of perspective. How a character is scaled depends on the perspective of the background. In some scenes the character only moves across the screen and so no change of scale is needed for the character. In some the character may move down a street and there is a high level of perspective. In some the character may move within a room and there is a small level of perspective.
Calculations regarding the scaling of the character needs to be calculated for each background scene. Perspective lines need to be drawn on the background and lengths measured.
The two examples below show how the scale for the character could be calculated.
In each case the scaling is based on the character as it is currently positioned on the screen. The variable y is a measure of how far the character is from its SMALLEST size position in the vertical direction. The variable h is a measure of the change in height of the character depending of y.
In the room scene the scale is > 1 since the character is currently at the back of the scene.
In the street scene the scale is < 1 since the character is currently at the from of the scene.
Triangular diagrams NOT to scale

I'm not sure what a DIV (I have no JavaScript experience) is but these links may help.
Perspective Projection
Walks you through the math used in perspective projections and includes some sample code (not JavaScript however).
3D Perspective Projection
Another page on perspective projection, with example code in C++.

I would do it like this:
// equation for objects appearing the same size
h=d*tan(α)
// now the scaling the size for arbitrary object
scale d h
1.0 d0 h0 // object with no scaling
0.5 2.0*d0 h0 // half size
0.25 4.0*d0 h0 // quoter size
0.5 d0 0.5 *h0
0.25 d0 0.25*h0
// so scale is:
scale = (d0/d)*(h/h0) // or
scale = (d0*h)/(d*h0)
set d0,h0 constants according to your view
d0 controls the magnification and h0=d0*tan(α)
If your camera has different view angle between axises then you have to apply two scaling factors
one for x axis and one for y axis
computed in the same way, but different angle used
d0 would be the same for both
Usual camera view angles in 3D are 60 or 90 degrees but in this case I would use 30 degrees
if you also view the underground then 60 with camera axis on the ground

In a true perspective projection, the scaling factor is given by S(D) = Df / D, where Df is the depth from the viewer to the full-size object and D the current depth.
For example, if a character is 40 pixels high and 16 large when seen in the foreground (assume 3m from the viewer), it will be 20 by 8 pixels at a depth of 6m and 10 by 4 at 12m.
Closer than the reference distance will result in magnification (80 by 32 at 1.5m).
[If your objects are located with (X, Y, Z) coordinates, X horizontal, Y vertical, Z perpendicular to the screen, pointing to the back, and is 0 at the depth of the screen, you have D = Z + Df and S(D) = Df / (Df + Z).]

Since you are talking about transforming a DIV then you should see CSS transforms. There are 2D transforms and 3D transforms. Keep in mind about the perspective attribute too ;)
Here you can find some examples:
http://desandro.github.io/3dtransforms/docs/perspective.html
http://24ways.org/2010/intro-to-css-3d-transforms/
http://dev.opera.com/articles/understanding-3d-transforms/
http://css-tricks.com/almanac/properties/t/transform/
http://css-tricks.com/almanac/properties/p/perspective/
http://css-tricks.com/almanac/properties/p/perspective-origin/

Related

3D Calculating the Z position of a point in a triangle

To create my three-dimensional engine, I used rasterization: dividing the triangles at their points.
However to carry out the rasterization I convert the points into the 2 dimensions. I then add the dot to a list that will render them later. To rearrange them, however, I need to know the Z position of the points.
So my question is: I have a triangle in 3 dimensions. I then convert it into the 2 dimensions. For each single point, how do I know the Z position, knowing its position of the 2 dimensions?
I tried a weird formula, which based on the distance from the points averaged the Z positions, but it's not working; Can you help me?

Resolve colliding rotated rectangles by moving along vector

I have a javascript program that places rectangles one at a time along walls in a room in counter-clockwise order. I use the coordinates of the rectangles corners for collision detection. It skips the placement of a rectangle if it intersects with another rectangle in the room.
(the room can be any shape so collisions can happen on any side of the rectangle)
However, I want to move the rectangle along the wall until it is no longer colliding instead of skipping it. My current idea is to move the rectangle 1 coordinate at a time in a loop until it no longer intersects, but it does not seem like a good solution for performance.
Is there a way to mathematically know how far in a given direction the rotated rectangle needs to be moved in order to no longer intersect another rotated rectangle?
Consider using of Separating Axis Theorem.
Two boxes (polygons in wide sense) don't intersect, if there exists some axis parallel to some box side, separating boxes, so the lie at distinct sides of this axis.
I've got arbitrary paper with good picture. At pages 16-17 we can see two boxes and some formulas to check for intersection.
You can express T - difference vector between box center as
T.x = pb.x - pa.x + t * dx
T.y = pb.y - pa.y + t * dy
where t is parameter (0 in the starting moment), and (dx, dy) is direction vector for B box moving (along the slanted wall at your picture).
Substituting T components into formula (note I changed > sign to =) we can get equation for parameter t corresponding to moment when Ax becomes separating axis.
| T • Ax | = WA + | ( WB*Bx ) • Ax | + |( HB*By ) • Ax |
If we make the same for other axes (Ay, Bx, By), we get 4 values of t, and the smallest positive one corresponds to minimal diplacement needed to separate the boxes.
Note that right part contains only constant values (for given setup), and we can easily calculate it using abs function, but left part contains variable, so we have to consider two cases (negative and positive dot product T • Ax) to find solution(s). Two possible solutions correspond to "left and right" box separation (anyway, you need smaller positive result)

Efficient algorithm for finding which hexagon a point belongs to

I'm trying to find a more efficient way of determining which hexagon a point belongs to from the following:
an array of points - for the sake of argument, 10000 points.
an array of center points of hexagons, approximately 1000 hexagons.
every point will belong to exactly one hexagon, some (most) hexagons will be empty.
The hexagons form a perfect grid, with the point of one hexagon starting in the top left corner (it will overlap the edge of the total area).
My current solution works, but is rather slow n * (m log m) I think, where n=length(points) and m=length(hexagons).
I suspect I can do much better than this, one solution that comes to mind is to sort (just once) both the points and the hexagons by their distance to some arbitrary point (perhaps the middle, perhaps a corner) then iterate over the points and over a subset of the hexagons, starting from the first hexagon whose distance to this point is >= to the last hexagon matched. Similarly, we could stop looking at hexagons once the distance difference between the (point -> ref point) and (hexagon center -> ref point) is larger than the "radius" of the hexagon. In theory, since we know that every point will belong to a hexagon, I don't even have to consider this possibility.
My question is: Is there a Much better way of doing it than this? In terms of complexity, I think it's worst case becomes marginally better n * m but the average case should be very good, probably in the region of n * 20 (e.g., we only need to look at 20 hexagons per point). Below is my current inefficient solution for reference.
points.forEach((p) => {
p.hex = _.sortBy(hexes, (hex) => {
const xDist = Math.abs(hex.middle.x - p.x);
const yDist = Math.abs(hex.middle.y - p.y);
return Math.sqrt((xDist * xDist) + (yDist * yDist));
})[0];
});
For an arbitrary point, you can find the nearest hexagon center in two steps (assuming the same arrangement as that of Futurologist):
divide the abscissa by the horizontal spacing between the centers, and round to the nearest integer.
divide the ordinate by the half of the vertical spacing, and round to the nearest even or odd integer, depending on the parity found above.
consider this center and the six ones around it, and keep the closest to the target point.
This gives you the indexes of the tile, in constant time.
Just a suggestion: assume you have the centers of each regular hexagon from your regular hexagonal grid (if I have understood correctly, that's part of the information you have).
-----
/ \
- ----- -----------> x - axis
\ / \
----- -
/ \ /
- -----
\ / \
----- -
| \ /
| -----
|
|
V
y - axis
You can think that your coordinate system starts from the center of the hexagon in the upper left corner and the y coordinate axis runs vertically down, while the x axis runs from left to right horizontally. The centers of the hexagons from your regular hexagonal grid form an image of the regular square grid, where the integer vertices of the square grid are transformed into the centers of the polygons by simply multiplying the coordinates of points in the square grid by the 2 x 2 square matrix (a sheer metrix)
A = a*[ sqrt(3)/2 0;
1/2 1 ]
where a is a parameter of the hexagonal grid, the distance between the centers of two edge-adjacent hexagons. This provides a way to assign integer indices [m n] to the grid formed by the hexagonal centers. After that, if you are given a point with coordinates [x y] in the hexagonal grid, you can apply the inverse matrix of A
[u; v] = A^(-1)*[x; y]
where
A^(-1) = (2/(a*sqrt(3)))*[ 1 0 ;
-1/2 sqrt(3)/2 ]
([x; y] and [u; v] are column vectors) and then take m = floor(u) and n = floor(v) to determine the integer coordinates (also the indices) [m = floor(u), n = floor(v)] of the upper left corner of the square cell from the square grid (observe that we have chosen the coordinates for both grids to start from the upper left corner). Thus, your point [u, v] is in the square with vertices [m,n] [m+1, n] [m, n+1] [m+1, n+1]
which means that the original point [x y] is in one of the four hexagons whose centers have indices [m,n] [m+1, n] [m, n+1] [m+1, n+1]. So you can use that to check in which of the four hexagons the point [x y] is.
I hope this helps.
Update: Leaving the below comment for posterity
I am now using the code provided here: https://www.redblobgames.com/grids/hexagons/
A really important note, is that your hexagon grid MUST start with the first hexagons mid point at (0, 0) - if it doesn't you get extremely odd results from this, which at first glance appeared as rounding errors (even after accounting for the expected offset). For me, it didn't matter where the first hexagon was positioned, so I just set it to be (0, 0) and it worked great.
Old solution
I'm still hoping for an optimal solution, but I ended up rolling my own which needs only check 6 hexagons per point, with a little overhead (approximately sqrt(m)) needed in addition.
With approximately 3000 points, and 768 hexagons (of which 310 were populated), it correctly assigned the point to the hexagon 100% of the time (as checked against a brute force approach) and took 29 milliseconds, compared to ~840 with brute force.
To start with, I store the hexagons in a map where the key is "${column},${row}". The columns technically overlap, so for the 0th row, the 0th column starts at -0.5 * hexWidth, and for row 1, the 0th column starts at 0px.
Next, I start from the position of the top left hexagon, item "0,0", which should also be at position 0, and increment y by either the height of the hexagon, or the edge length of the hexagon accordingly. When the y is > the points y, I've found the probable row, I then check the row above and below.
For the column within the row, I take the both the Math.floor and Math.ceil of x / hexWidth.
Doing this gives 6 hexagons to check, from this point the solution is identical to the solution in the question.
In theory, this could be used to just look up the correct hexagon, using the x/y position. However in practice, this didn't work for me about 5% of the time with off by 1 errors, likely a rounding problem.
Some other things I looked at:
As suggested by #jason-aller, https://www.redblobgames.com/grids/hexagons/#rounding. Unfortunately, this seems to assume some form of transformation on the hex grid (rotations) and is not easy to follow - continually referencing functions which have yet to be defined.
QuadTree (various implementations) unfortunately, this returned approximately 100 "potential matches" for each point - so the performance improvement was not good. I'm aware that insertion order changes how useful QuadTree is, I tried natural order, sorted by distance from top, left and shuffled, they all performed equally badly. It's likely that an optimal solution with QuadTree would involve populating the tree with the item closest to the mid point, then the items 1/2 from the mid point to each corner, recursively. Too much like hard work for me!

How to divide an ellipse to equal segments?

This calculates vertex coordinates on ellipse:
function calculateEllipse(a, b, angle)
{
var alpha = angle * (Math.PI / 180) ;
var sinalpha = Math.sin(alpha);
var cosalpha = Math.cos(alpha);
var X = a * cosalpha - b * sinalpha;
var Y = a * cosalpha + b * sinalpha;
}
But how can I calculate the "angle" to get equal or roughly equal circumference segments?
So from what Jozi's said in the OP's comments, what's needed isn't how to subdivide an ellipse into equal segments (which would require a whole bunch of horrible integrals), it's to construct an ellipse from line segments of roughly equal length.
There are a whole pile of ways to do that, but I think the best suited for the OP's purposes would be the concentric circle method, listed on the page as 'the draftman's method'. If you don't mind installing the Mathematica player, there's a neat lil' app here which illustrates it interactively.
The problem with those methods is that the segment lengths are only roughly equal at low eccentricities. If you're dealing in extreme eccentricities, things get a lot more complicated. The simplest solution I can think of is to linearly approximate the length of a line segment within each quadrant, and then solve for the positions of the endpoints in that quadrant exactly.
In detail: this is an ellipse quadrant with parameters a = 5, b = 1:
And this is a plot of the length of the arc subtended by an infinitesimal change in the angle, at each angle:
The x axis is the angle, in radians, and the y axis is the length of the arc that would be subtended by a change in angle of 1 radian. The formula, which can be derived using the equations in the Wikipedia article I just linked, is y = Sqrt(a^2 Sin^2(x) + b^2 Cos^2(x)). The important thing to note though is that the integral of this function - the area under this curve - is the length of the arc in the whole quadrant.
Now, we can approximate it by a straight line:
which has gradient m = (a-b) / (Pi/2) and y intercept c = b. Using simple geometry, we can deduce that the area under the red curve is A = (a+b)*Pi/4.
Using this knowledge, and the knowledge that the area under the curve is the total length of the curve, the problem of constructing an approximation to the ellipse reduces to finding say a midpoint-rule quadrature (other quadratures would work too, but this is the simplest) of the red line such that each rectangle has equal area.
Converting that sentence to an equation, and representing the position of a rectangle in a quadrature by it's left hand boundary x and its width w, we get that:
(v*m)*w^2 + (m*x+c)*w - A/k == 0
where k is the number of pieces we want to use to approximate the quadrant, and v is a weighting function I'll come to shortly. This can be used to construct the quadrature by first setting x0 = 0 and solving for w0, which is then used to set x1 = w0 and solve for w1. Then set x2 = w1, etc etc until you've got all k left-hand boundary points. The k+1th boundary point is obviously Pi/2.
The weighting function v effectively represents where the rectangle crosses the red line. A constant v = 0.5 is equivalent to it crossing in the middle, and gets you this with 10 points:
but you can play around with it to see what better balances the points. Ideally it should stay in the range [0, 1] and the sum of the values you use should be k/2.
If you want an even better approximation without messing around with weighting functions, you could try least-squares fitting a line rather than just fitting it to the endpoints, or you could try fitting a cubic polynomial to the blue curve instead of a linear polynomial. It'll entail solving quartics but if you've a maths package on hand that shouldn't be a problem.
Too long for a comment, so I suppose this has to be an answer ...
Here's a mathematically simple approach to forming a first order approximation. Pick one quadrant. You can generate the data for the other quadrants by reflection in the X and Y axis. Calculate (x,y) for the angle = 0 degrees, 1 degree, ... 90 degrees. Now you want the little lengths joining consecutive points. If (x_n, y_n) are the coordinates at angle = n, then Pythagoras tells us the distance D between points (x_n, y_n) and (x_n+1, y_n+1) is D = sqrt((x_n+1 - x_n)^2 + (y_n+1 - y_n)^2). Use this formula to produce a table of cumulative distances around the ellipse for angles from 0 degrees to 90 degrees. This is the inverse of the function you seek. Of course, you don't have to pick a stepsize of 1 degree; you could use any angle which exactly divides 90 degrees.
If you want to find the angle which corresponds to a perimeter step size of x, find the largest angle n in your table producing a partial perimeter less than or equal to x. The partial perimeter of angle n+1 will be larger than x. Use linear interpolation to find the fractional angle which corresponds to x.
All we are doing is approximating the ellipse with straight line segments and using them instead of the original curve; its a first order approximation. You could do somewhat better by using Simpson's rule or similar instead of linear interpolation.
Yes, you have to calculate the table in advance. But once you have the table, the calculations are easy. If you don't need too much accuracy, this is pretty simple both mathematically and coding-wise.

ATAN calculation fails when values are scaled

Im animating sprites w javacript - these sprites consist of a container DIV and the firstChild is an absolute positioned IMG. The image is comprised of 16 vertical views/angles of the object. When the object moves from A to B, the ATAN2 function calculates the style=top: value appropriate to the direction the object is traveling in. This all works except for another aspect of the sprite - they can change their size. The default size of the sprite is 24px (wide) and this does work with ATAN2, but as soon as the sprite is made bigger the calculation misaligns the sprite's frame-strip. Below is the code, x1 - y1 are the from and to positions, while s is the size (width). the value 128 is the maximum size - and the bracked values are of a sprite allowed and the last calculation assumes this, then computes for the actual size with *(s/128) ...
function P_angle(x1,x2,y1,y2,s)
{
var v=parseInt(Math.atan2(x2-x1,y2-y1)/(Math.PI/180)+180)
return (v>348.75?0:v>326.25?-128:v>303.75?-256:v>281.25?-384:v>258.75?-512:v>236.25?-640:v>213.75?-768:v>191.25?-896:v>168.75?-1024:v>146.25?-1152:v>123.75?-1280:v>101.25?-1408:v>78.75?-1536:v>56.25?-1664:v>33.75?-1792:v>11.25?-1920:0)*(s/128);
}
In the first line you do a floating point calculation and pass the result to a function expecting a string argument... you are saved by implicit conversion, but it's ugly.
The huge conditional in your second line rounds the angle off to the nearest multiple of 22.5 degrees, wrapping around and mapping to negative multiples of 128, then multiplies it with s divided by 128... was it originally designed for 128 pixel sprites? Anyway, you should just be able to do this:
function P_angle(x1,x2,y1,y2,s)
{
return s*(Math.round(Math.atan2(x2-x1,y2-y1)*(8/Math.PI)-8)%16);
}
You don't say how large the misalignment is with your original code, but I suspect it is caused by rounding errors when dividing out the 128 factor, and that you were just lucky that everything rounded right for 24 pixel sprites. With the version here, you are certain to return an exact multiple of s.

Categories

Resources