Find the center-coordinates of a rotated rectangle - computational-geometry

I am having trouble with finding the X and Y-coordinates of the center of a rotated rectangle through mathematical calculations.
What I have is the width 'A' and height 'B' of a rectangle, as well as its rotation 'R' in degrees.
What would be the formula to calculate those points?
Here is a sketch to further explain what i am trying to do:
Any help is greatly appreciated! :)

if you are trying to do it in pure way, by your self
it think this answer would be great for you
https://math.stackexchange.com/questions/270194/how-to-find-the-vertices-angle-after-rotation
if you want to use a package for this, then I do recommend
flatten-js , geometric ,Ecluid.ts

I doubt that this is what you are after, but here is a solution to a possibly related question.
We assume that the leftmost corner lies on the Y axis, and the bottommost on the X axis. Thus, the coordinates of these corners are (0, B sin R) and (B cos R, 0) respectively. The midpoint of the bottom side is (B/2 cos R, B/2 sin R). To this we add a vector of length A/2 in the orthogonal direction and obtain the coordinates of the center:
(B/2 cos R - A/2 sin R, B/2 sin R + A/2 cos R)

Related

Raycast Players Distance to Grid Intersection

I am programming a raycaster in JavaScript. I am having trouble finding or implementing an algorithm for the raycast. Currently I am trying out the cast in the following style.
Theres an grid with equal block width and height. My player has a position within the grid, a direction as an angle 0 - 360 degrees where hes looking at. In the first step I need to figure out the distace from my Player to the Green dot at the Grid Intersection. I know that the Green Point is at the Intersection therefore i can figure out the length of the red line. Theres an right angle at the intersection. When I ve calculated the distance or x and y position of the green dot I have to do a simular thing in the 2nd step. The distance of the orange line is known, the position of the green dot and the angle is known. Again the right angle is on the intersecting border line.
I am not even sure if its possible this way, but maybe you got any other idea how I should then work it out. Thank you very much.
(Apologies for formatting below; I'm tapping this out on a phone)
From trigonometry, cos(aplha) = (length of red line)/(length of hypotenuse).
Therefore: length of hypotenuse = (length of red line)/cos(alpha).
You'd use sin for a vertical intersection.
A word of caution though: if you think about what would happen when the player is looking directly at a wall, all the lengths should be the same so that it's a constant height on screen, but they'll actually be different because the diagonals are different. You need to multiply by cos of the relative angle between the player's direction and the casting direction (so, if you've a 60 degree field of view then 0 at the centre of the display, off to +30 at one end and down to -30 at the other).
Also don't fall into the common trap of thinking that the angles you cast at should be evenly spaced. Think again of a person looking directly at a wall and use atan to get the proper relative angles.
The parametric equations of the ray read
X = x + t cos α, Y = y + t sin α
with t>0.
Assuming a unit grid (but you can rescale), and the angle in the first quadrant, the first intersections with the grid are
X = ceiling(x) => t = (X - x) / cos α => Y = y + (X - x) . tan α
and
Y = ceiling(y) => t = (Y - y) / sin α => X = x + (Y - y) . cot α
The smallest of the two t will tell you which of the horizontal and vertical is met first.
The next intersections are with X = ceiling(x) + i, and Y = ceiling(y) + j, hence the Y increase in steps tan α and the X in steps cot α.
For the other quadrants, the ceiling's are replaced by floor's.

Efficient method to check if point is within a diamond

I have an array of diamonds as shown in the image and I know the position of every diamond and the distance from the origin of the diamond to any vertex (They are all the same distance from the center). I am also given a point. Given that information what is the most efficient method to find which diamond the point is in.
I know that I can just check the distance of the point from the position of every diamond but that seems way too cpu intensive as I have to do this multiple times.
Also, this shouldn't matter, but I am using C# and Unity 3D to do this.
If your diamonds form a regular pattern as in your picture, then just perform coordinate transformation to rotate the whole thing 45 degrees CW or CCW with (0, 0) as the origin. After that the problem becomes trivial: locating a point in a regular orthogonal grid.
Diamonds border line have equations
x + y = a0 + u * Size
y - x = b0 + v * Size
where a0, b0 are coordinates of the some vertex of base diamond (that has cell coordinates 0, 0), u and v are cell coordinates, Size is edge length. So to find what diamond point (px, py) belongs to, you can calculate
u = Floor((px + py - a0) / Size))
v = Floor((py - px - b0) / Size))

How to determine a semi-sphere's point x-y-z coordinates?

I'm having serious problems solving a problem illustrated on the pic below.
Let's say we have 3 points in 3D space (blue dots), and the some center of the triangle based on them (red dot - point P). We also have a normal to this triangle, so that we know which semi-space we talking about.
I need to determine, what is the position on a point (red ??? point) that depends on two angles, both in range of 0-180 degrees. Doesnt matter how the alfa=0 and betha=0 angle is "anchored", it is only important to be able to scan the whole semi-sphere (of radius r).
http://i.stack.imgur.com/a1h1B.png
If anybody could help me, I'd be really thankful.
Kind regards,
Rav
From the drawing it looks as if the position of the point on the sphere is given by a form of spherical coordinates. Let r be the radius of the sphere; let alpha be given relative to the x-axis; and let beta be the angle relative to the x-y-plane. The Cartesian coordinates of the point on the sphere are:
x = r * cos(beta) * cos(alpha)
y = r * cos(beta) * sin(alpha)
z = r * sin(beta)
Edit
But for a general coordinate frame with axes (L, M, N) centered at (X, Y, Z) the coordinates are (as in dmuir's answer):
(x, y, z) =
(X, Y, Z)
+ r * cos(beta) * cos(alpha) * L
+ r * cos(beta) * sin(alpha) * M
+ r * sin(beta) * N
The axes L and N must be orthogonal and M = cross(N, L). alpha is given relative to L, and beta is given relative to the L-M plane. If you don't know how L is related to points of the triangle, then the question can't be answered.
You need to find two unit length orthogonal vectors L, M say, in the plane of the triangle as well as the the unit normal N. The points on the sphere are
r*cos(beta)*cos(alpha) * L + r*cos(beta)*sin(alpha)*M + r*sin(beta)*N

How to detect if an ellipse intersects(collides with) a circle

I want to improve a collision system.
Right now I detect if 2 irregular objects collide if their bounding rectangles collide.
I want to obtain the for rectangle the corresponding ellipse while for the other one to use a circle. I found a method to obtain the ellipse coordinates but I have a problem when I try to detect if it intersects the circle.
Do you know a algorithm to test if a circle intersects an ellipse?
Short answer: Solving exactly for whether the two objects intersect is complicated enough to be infeasible for the purpose of collision detection. Discretize your ellipse as an n-sided polygon for some n (depending on how accurate you need to be) and do collision detection with that polygon.
Long answer: If you insist on determining if the smooth ellipse and circle intersect, there are two main approaches. Both involve solving first for the closest point to the circle's center on the ellipse, and then comparing that distance to the circle's radius.
Approach 1: Use a parametrization of the ellipse. Transform your coordinates so that the ellipse is at the origin, with its axes aligned to the x-y axes. That is:
Center of ellipse: (0,0)
Center of circle: c = (cx, cy)
Radius of circle: r
Radius of x-aligned axis of ellipse: a
Radius of y-aligned axis of ellipse: b.
The equation of the ellipse is then given by a cos(t), b sin(t). To find the closest point, we want to minimize the square distance
|| (a cos t, b sin t) - c ||^2. As Jean points out, this is "just calculus": take a derivative, and set it equal to 0. Unless I'm missing something, though, solving the resulting (quite nasty) equation for t is not possible analytically, and must be approximated using e.g. Newton's Method.
Plug in the t you find into the parametric equation to get the closest point.
Pro: Numerical solve is only in one variable, t.
Con: You must be able to write down a parametrization of the ellipse, or transform your coordinates so that you can. This shouldn't be too hard for any reasonable representation you have of the ellipse. However, I'm going to show you a second method, which is much more general and might be useful if you have to generalize your problem to, say, 3D.
Approach 2: Use multidimensional calculus. No change of coordinates is necessary.
Center of circle: c = (cx, cy)
Radius of cirlce: r
Ellipse is given by g(x, y) = 0 for a function g. For instance, per Curd's answer you might use g(x,y) = distance of (x,y) from focus 1 + distance of (x,y) from focus 2 - e.
Finding the point on the ellipse closest to the center of the circle can then be phrased as a constrained minimization problem:
Minimize ||(x,y) - c||^2 subject to g(x,y) = 0
(Minimizing the square distance is equivalent to minimizing the distance, and much more pleasant to deal with since it's a quadratic polynomial in x,y.)
To solve the constrained minimization problem, we introduce Lagrange multiplier lambda, and solve the system of equations
2 * [ (x,y) -c ] + lambda * Jg(x,y) = 0
g(x,y) = 0
Here Jg is the gradient of g. This is a system of three (nonlinear) equations in three unknowns: x, y, and lambda. We can solve this system using Newton's Method, and the (x,y) we get is the closest point to the circle's center.
Pro: No parametrization needs to be found
Pro: Method is very general, and works well whenever writing g is easier than finding a parametric equation (such as in 3D)
Con: Requires a multivariable Newton solve, which is very hairy if you don't have access to a numerical method package.
Caveat: both of these approaches technically solve for the point which extremizes the distance to the circle's center. Thus the point found might be the furthest point from the circle, and not the closest. For both methods, seeding your solve with a good initial guess (the center of the circle works well for Method 2; you're on your own for Method 1) will reduce this danger.
Potential Third Approach?: It may be possible to directly solve for the roots of the system of two quadratic equations in two variables representing the circle and ellipse. If a real root exists, the objects intersect. The most direct way of solving this system, again using a numerical algorithm like Newton's Method, won't help because lack of convergence does not necessary imply nonexistence of a real root. For two quadratic equations in two variables, however, there may exist a specialized method that's guaranteed to find real roots, if they exist. I myself can't think of a way of doing this, but you may want to research it yourself (or see if someone on stackoverflow can elaborate.)
An ellipse is defined a the set of points whose
sum of the distance to point A and the distance to point B is constant e.
(A and B are called the foci of the ellipse).
All Points P, whose sum AP + BP is less than e, lie within the ellipse.
A circle is defined as the set of points whose
distance to point C is r.
A simple test for intersection of circle and ellipse is following:
Find
P as the intersection of the circle and the line AC and
Q as the intersection of the circle and the line BC.
Circle and ellipse intersect (or the circle lies completely within the ellipse) if
AP + BP <= e or AQ + BQ <= e
EDIT:
After the comment of Martin DeMello and adapting my answer accordingly I thought more about the problem and found that the answer (with the 2nd check) still doesn't detect all intersections:
If circle and ellipse are intersecting only very scarcely (just a little more than being tangent) P and Q will not lie within the ellipse:
So the test described above detects collision only if the overlap is "big enough".
Maybe it is good enough for your practical purposes, although mathematically it is not perfect.
I know that it's too late but I hope it would help somebody. My approach to solve this problem was to interpolate the ellipse into an n-dimensions polygon, then to construct a line between every 2 points and find whether the circle intersects with any of the lines or not. This doesn't provide the best performance, but it is handy and easy to implement.
To interpolate the ellipse to an n-dimensions polygon, you can use:
float delta = (2 * PI) / n;
std::vector<Point*> interpolation;
for(float t = 0; t < (2 * PI); t += delta) {
float x = rx * cos(t) + c->get_x();
float y = ry * sin(t) + c->get_y();
interpolation.push_back(new Point(x, y));
}
c: The center of the ellipse.
rx: The radius of x-aligned axis of the ellipse.
ry: The radius of y-aligned axis of the ellipse.
Now we have the interpolation points, we can find the intersection between the circle and the lines between every 2 points.
One way to find the line-cricle intersection is described here,
an intersection occurs if an intersection occurred between any of the lines and the circle.
Hope this helps anybody.
find the point on the ellipse closest to the center of the circle
and then check if the distance from this point is smaller than the radius of the circle
if you need help doing this just comment, but it's simply calculus
edit: here's a ways towards the solution, since there is something wrong with curds
given center α β on the ellipse
and (for lack of remembering the term) x radius a, y radius b
the parametrization is
r(Θ) = (ab)/( ( (BcosΘ)^2 + (asinΘ)^2 )^.5)
x(Θ) = α + sin(Θ)r(Θ)
y(Θ) = β + cos(Θ)r(Θ)
and then just take the circle with center at (φ, ψ) and radius r
then the distance d(Θ) = ( (φ - x(Θ))^2 + (ψ - y(Θ) )^2)^.5
the minimum of this distance is when d'(Θ) = 0 (' for the derivative)
d'(Θ) = 1/d(Θ) * (-φx'(Θ) + x(Θ)x'(Θ) - ψy'(Θ) + y(Θ)y'(Θ) )
==>
x'(Θ) * (-φ + x(Θ)) = y'(Θ) * (ψ - y(Θ))
and keep going and going and hopefully you can solve for Θ
The framework you're working in might have things to help you solve this, and you could always take the easy way out and approximate roots via Newton's Method
if a circle and an ellipse collide, then either their boundaries intersect 1, 2, 3, or 4 times(or infinitely many in the case of a circular ellipse that coincides with the circle), or the circle is within the ellipse or vice versa.
I'm assuming the circle has an equation of (x - a)^2 + (y - b)^2 <= r^2 (1) and the ellipse has an equation of [(x - c)^2]/[d^2] + [(y - e)^2]/[f^2] <= 1 (2)
To check whether one of them is inside the other, you can evaluate the equation of the circle at the coordinates of the center of the ellipse(x=c, y=e), or vice versa, and see if the inequality holds.
to check the other cases in which their boundaries intersect, you have to check whether the system of equations described by (1) and (2) has any solutions.
you can do this by adding (1) and (2), giving you
(x - a)^2 + (y - b)^2 + [(x - c)^2]/[d^2] + [(y - e)^2]/[f^2] = r^2 + 1
next you multiply out the terms, giving
x^2 - 2ax + a^2 + y^2 - 2by + b^2 + x^2/d^2 - 2cx/d^2 + c^2/d^2 + y^2/f^2 - 2ey/f^2 + e^2/f^2 = r^2 + 1
collecting like terms, we get
(1 + 1/d^2)x^2 - (2a + 2c/d^2)x + (1 + 1/f^2)y^2 - (2b + 2e/f^2)y = 1 + r^2 - a^2 - b^2 - c^2/d^2 - e^2/f^2
now let m = (1 + 1/d^2), n = -(2a + 2c/d^2), o = (1 + 1/f^2), and p = -(2b + 2e/f^2)
the equation is now mx^2 + nx + oy^2 + py = 1 + r^2 - a^2 - b^2 - c^2/d^2 - e^2/f^2
now we need to complete the squares on the left hand side
m[x^2 + (n/m)x] + o[y^2 + (p/o)y] = 1 + r^2 - a^2 - b^2 - c^2/d^2 - e^2/f^2
m[x^2 + (n/m)x + (n/2m)^2 - (n/2m)^2] + o[y^2 + (p/o)y + (p/2o)^2 - (p/2o)^2] = 1 + r^2 - a^2 - b^2 - c^2/d^2 - e^2/f^2
m[(x + n/2m)^2 - (n/2m)^2] + o[(y + p/2o)^2 - (p/2o)^2] = 1 + r^2 - a^2 - b^2 - c^2/d^2 - e^2/f^2
m(x + n/2m)^2 - m(n/2m)^2 + o(y + p/2o)^2 - o(p/2o)^2 = 1 + r^2 - a^2 - b^2 - c^2/d^2 - e^2/f^2
m(x + n/2m)^2 + o(y + p/2o)^2 = 1 + r^2 - a^2 - b^2 - c^2/d^2 - e^2/f^2 + m(n/2m)^2 + o(p/2o)^2
this system has a solution iff 11 + r^2 - a^2 - b^2 - c^2/d^2 - e^2/f^2 + m(n/2m)^2 + o(p/2o)^2 >= 0
There you have it, if I didn't make any algebraic mistakes. I don't know how much you can simplify the resulting expression, so this solution might be quite computationally expensive if you're going to check for many circles/ellipses
Enlarge the ellipse's major and minor radii by the radius of the circle. Then test if the center of the given circle is within this new larger ellipse by summing the distances to the foci of the enlarged ellipse.
This algorithm is quite efficient. You can early-out if the given circle doesn't intersect a circle which circumscribes the ellipse. This is slower than a bounding box test, but finding the bounding box of a non-axis-aligned ellipse is tricky.
Forget about a mathematical solution. As you can easily see by drawing, you can have up to four solutions, and thus likely a fourth grade polynomial.
Instead just do a binary search along the edge of one of the figures. It is easy to determine if a point lies within an ellipse and even more so in a circle (just see if distance is shorter than radius).
If you really want to go for the maths, Wolfram MathWorld has a nice article here: http://mathworld.wolfram.com/Circle-EllipseIntersection.html but be warned, you'll still have to write a polynomial equation solver, probably using something like binary search.
Supposing:
the ellipse is centred at the origin and with the semi-major
axis (of length a) oriented along the x axis, and with a semi-minor
axis of length b; E2 is the eccentricity squared, ie (aa-bb)/(a*a);
the circle is centred at X,Y and of radius r.
The easy cases are:
the circle centre is inside the ellipse (ie hypot(X/a, Y/b) <= 1)
so there is an intersection;
the circle centre is outside a circle centred at 0 of radius a+r
(ie hypot(X,Y) > a+r) so there isn't an intersection.
One approach for the other cases is to compute the geodetic
coordinates (latitude, height) of the circle centre. The circle
intersects the ellipse if and only if the height is less than the radius.
The geodetic latitude of a point on an ellipse is the angle
the normal to the ellipse at the point makes with the x axis, and
the height of a point outside the ellipse is the distance of the
point from the point on the ellipse closest to it. Note the geodetic latitude is not same as the polar angle from the ellipse centre to the point unless the
ellipse is in fact circular.
In formulae the conversion from geodetic coordinates lat,ht to
cartesian coordinates X,Y is
X = (nu+ht)*cos(lat), Y = (nu * (1-E2) + ht)*sin(lat)
where nu = a/sqrt( 1 - E2*sin(lat)sin(lat)).
The point on the ellipse closest to X,Y is the point
with the same latitude, but zero height, ie x = nucos(lat),
y = nu * (1-E2) * sin(lat).
Note that nu is a function of latitude.
Unfortunately the process of finding lat,ht from X,Y is an
iterative one. One approach is to first find the latitude, and then
the height.
A little algebra shows that the latitude satisfies
lat = atan2( Y+ E2*nusin(lat), X)
which can be used to compute successive approximations to the latitude,
starting at lat = atan2( Y, X(1.0-E2)), or (more efficiently) can be
solved using newton's method.
The larger E2 is, ie the flatter the ellipse is, the more
iterations will be required. For example if the ellipse is nearly
circular (say E2<0.1) then five iterations will get x,y below
to within a*1e-12, but if the ellipse is very flat, e.g. E2=0.999
you'll need around 300 iterations to get the same accuracy!
Finally, given the latitude, the height can be computed
by computing (x,y):
x = nucos(lat), y = nu(1-E2)*sin(lat)
and then h is the distance from x,y to the circle centre,
h = hypot( X-x, Y-y)
This isn't that hard. user168715's answer is generally right, but doing calculus isn't necessary. Just trigonometry.
Find the angle between the center of the two objects. Using this you can find the closest point to the circle's center on the ellipse using the polar-form:
(Taken from Wikipedia article on Ellipses)
Now compare the distance between the two object centers, subtracting the ellipse radius and circle radius.
Maybe I'm missing something; maybe ArcTan/Cos/Sin are slow -- but I don't think so, and there should be fast-approximations if needed.
I wanted to provide some input into the more general problem involving contact between two ellipses. Calculating the distance of closest approach of two ellipses was a long standing problem and was only solved analytically within the last ten years-it is by no means simple. The solution to the problem may be found here http://www.e-lc.org/docs/2007_01_17_00_46_52/.
The general method to determine if there is contact between two ellipses is to first calculate the distance of closest approach of the ellipses in their current configuration and then subtract this from their current magnitude of separation. If this result is less than or equal to 0, then they are in contact.
If anyone is interested I can post code that calculates the distance of closest approach--it's in C++. The code is for the general case of two arbitrary ellipses, but you can obviously do it for a circle and ellipse, since a circle is an ellipse with equal minor and major axes.

Best way to find a point on a circle closest to a given point

Given a point (pX, pY) and a circle with a known center (cX,cY) and radius (r), what is the shortest amount of code you can come up with to find the point on the circle closest to (pX, pY) ?
I've got some code kind of working but it involves converting the circle to an equation of the form (x - cX)^2 + (y - cY)^2 = r^2 (where r is radius) and using the equation of the line from point (pX, pY) to (cX, cY) to create a quadratic equation to be solved.
Once I iron out the bugs it'll do, but it seems such an inelegant solution.
where P is the point, C is the center, and R is the radius, in a suitable "mathy" language:
V = (P - C); Answer = C + V / |V| * R;
where |V| is length of V.
OK, OK
double vX = pX - cX;
double vY = pY - cY;
double magV = sqrt(vX*vX + vY*vY);
double aX = cX + vX / magV * R;
double aY = cY + vY / magV * R;
easy to extend to >2 dimensions.
i would make a line from the center to the point, and calc where that graph crosses the circle oO i think not so difficult
Solve it mathematically first, then translate into code. Remember that the shortest line between a point and the edge of a circle will also pass through its center (as stated by #litb).
The shortest distance point lies at the intersection of circumference and line passing through the center and the input point. Also center, input and output points lie on a straight line
let the center be (xc, yc) and shortest point from input (xi, yi) be (x,y) then
sqrt((xc-x)^2 + (yc-y)^2) = r
since center, input and output points lie on a straight line, slope calculated between
any of two of these points should be same.
(yc-yi)/(xc-xi) = (y-yc)/(x-xc)
4.solving equations 2&3 should give us the shortest point.
Trig functions, multiply by r, and add pX or pY as appropriate.
Treat the centre of the circular as your origin, convert the co-ordinates of (pX, pY) to polar co-ordinates, (theta, r') replace r' with the original circle's r and convert back to cartesian co-ordinates (and adjust for the origin).
You asked for the shortest code, so here it is. In four lines it can be done, although there is still a quadratic.
I've considered the point to be outside the circle.
I've not considered what happens if the point is directly above or below the circle center, that is cX=pX.
m=(cY-pY)/(cX-pX); //slope
b=cY-m*cX; //or Py-m*Px. Now you have a line in the form y=m*x+b
X=( (2mcY)*((-2*m*cY)^2-4*(cY^2+cX^2-b^2-2*b*cY-r^2)*(-1-m^2))^(1/2) )/(2*(cY^2+cX^2-b^2-2*bc*Y-r^2));
Y=mX+b;
1] Get an equation for a line connecting the point and the circle center.
2] Move along the line a distance of one radius from the center to find the point on the circle. That is: radius=a^2+b^2 which is: r=((cY-Y)+(cX-X))^(1/2)
3] Solve quadratically. X=quadratic_solver(r=((cY-Y)+(cX-X))^(1/2),X) which if you substitute in Y=m*X+b you get that hell above.
4] X and Y are your results on the circle.
I am rather certain I have made an error somewhere, please leave a comment if anyone finds something. Of course it is degenerate, one answer is furthest from your point and the other is closest.
Easy way to think about it in terms of a picture, and easy to turn into code: Take the vector (pX - cX, pY - cY) from the center to the point. Divide by its length sqrt(blah blah blah), multiply by radius. Add this to (cX, cY).
Here is a simple method I use in unity... for the math kn00bs amongst us.
Its dependent on the transform orientation but it works nicely. I am doing a postion.z = 0 but just fatten the axis of the 2d circle you are not using.
//Find closest point on circle
Vector3 closestPoint = transform.InverseTransformPoint(m_testPosition.position);
closestPoint.z = 0;
closestPoint = closestPoint.normalized * m_radius;
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.TransformPoint(closestPoint), 0.01f);

Resources