Rotating a point around another point - c++

I'm trying to rotate one point around a central point by an angle - standard problem. I've seen lots of posts about this but I can't get my implementation to work:
void Point::Rotate(const Point Pivot, const float Angle)
{
if (Angle == 0)
return;
float s = sin(Angle);
float c = cos(Angle);
x -= Pivot.x;
y -= Pivot.y;
x = (x * c) - (y * s) + Pivot.x;
y = (x * s) + (y * c) + Pivot.y;
}
This is my code, the logic of which I've gleaned from numerous source, for example here, and here.
As far as I'm aware, it should work. However, when I apply it to rotating for example, the point (0, 100) by 90 degrees (Pi/2 is given to the function) around (0, 0), the rotated point is apparently at (-100, -100); 100px below where it should be.
When trying to draw a circle (36 points) - it creates a vague heart shape. It looks like a graph I saw that I think was in polar coordinates - do I need to convert my point to Cartesian or something?
Can anyone spot anything wrong with my code?
Edit: Sorry, this function is a member function to a Point class - x and y are the member variables :/

You're almost there, but you're modifying x in the next-to-last line, meaning that the value of that coordinate fed into the y calculation is incorrect!
Instead, use temporary variables for the new x and y and then add the Pivot coordinates on afterwards:
double nx = (x * c) - (y * s);
double ny = (x * s) + (y * c);
x = nx + Pivot.x;
y = ny + Pivot.y;

Related

Find 2 points based off how much a point has rotated around a center point

I am making a little game and I am now working on a "radar". Now to do this I need to find two points based off how much a point has rotated around a center point.
A is going to rotate around C.
As A rotates around C, B & D will move along with A and stay in the same "positions" based off of where A is.
So for example, if A rotates around C 90 degrees B & D would then move and be in this position
But I am not very good at trig, so I don't really know the math I would need in order to find B & D based off how much A has rotated around C.
How do i find B & D based off of how much A has rotated around C?
I would image the final math would look somewhat similar to this:
float * returnB(float * APoint, float * CPoint)
{
float B_Out[2];
//calculate where B is based off A & C
B_Out[0] = B_X;
B_Out[1] = B_Y;
return B_Out;
}
float B[2];
B[0] = returnB(A,C)[0];
B[1] = returnB(A,C)[1];
float * returnD(float * APoint, float * CPoint)
{
float D_Out[2];
//calculate where D is based off A & C
D_Out[0] = D_X;
D_Out[1] = D_Y;
return D_Out;
}
float D[2];
D[0] = returnD(A,C)[0];
D[1] = returnD(A,C)[1];
You can rotate a point (x, y) around the origin by performing a simple matrix multiplication, which gives the following equations for the transformed point (x0, y0):
x0 = x * cos(theta) - y * sin(theta);
y0 = x * sin(theta) + y * cos(theta);
So you know A's relative 2d position respect to C. Lets say it is (ax, ay).
If you cross product(0,0,1) with (ax, ay, 0) you will find relative position of D that will be something like (dx, dy, 0)
d = (dx, dy) is relative position of D.
b is also -d
https://en.wikipedia.org/wiki/Cross_product

Given two points, find a third point on the line

I have two points A (x1,y1) and B (x2,y2) that are given as an input to the program. I have to find a third point C that lies on the line AB and is at a distance 10 away from the point A.
I can easily get the slope of the line but that doesn't give me the full equation for the line. Even if I get the full equation, I am not sure using this equation, how would I find out a point that is x distance away from A.
Any suggestions on how to approach this?
There are always two points on each line:
get the vector from A to B (subtract the coordinates)
normalize the vector (divide by its length; pythagorean theorem)
multiply the vector by 10 or -10
add the vector to A to get C
Note that if A==B, the line is not defined, and this algorithm causes a division by zero. You may want to add a test for equality at the beginning.
You can use the sine or the cosine (times 10) of the angle of the line to get the horizontal or vertical distance of the point that is a distance of 10 from a given point. A shortcut is to use the horizontal or vertical distance divided by the direct distance between the points to get the sine or cosine.
You can do it using vectors like this:
Let D = the difference between B and A (D = B - A)
Then any point on the line can be described by this formula:
point = A + Dt
where t is a real number.
So just plug in any value for t to get another point. For example if you let t == 1 then the equation above reduces to point = B. If you let t = 0 then it reduces to point = A. So you can see that you can use this to find a point between A and B simply by let t range from 0 to 1. Additionally if you let t > 1, you will find a point past B.
You can see from the image that your given points are x1,y1 and x2,y2. You need to find an intermediate point at a distance 'R' from point x1,y1.
All you need to do is to find θ using
Tan θ = (y2-y1)/(x2-x1)
Then you can get the intermediate point as (R * cos θ),(R * Sin θ)
I have drawn this assuming positive slope.
Going on similar lines you can seek a solution for other special cases lile:
i. Horizontal line
ii. Vertical line
iii. Negative slope
Hope it clarifies.
I have done the calculation in Andengine using a Sprite object. I have two Array List x coordinates and y coordinates. Here i am just calculating using the last two values from these two array list to calculate the third point 800 pixel distant from Your point B. you can modify it using different values other than 800. Hope it will work.The coordinate system here is a little different where (0,0) on the top left corner of the screen. Thanks
private void addExtraCoordinate(CarSprite s) {
int x0, y0, x1, y1;
float x = 0f, y = 0f;
x0 = Math.round(xCoordinates.get(xCoordinates.size() - 2));
x1 = Math.round(xCoordinates.get(xCoordinates.size() - 1));
y0 = Math.round(yCoordinates.get(yCoordinates.size() - 2)) * (-1);
y1 = Math.round(yCoordinates.get(yCoordinates.size() - 1)) * (-1);
if (x1 == x0 && y1 == y0) {
return;
} else if (y1 == y0 && x1 != x0) {
if (x1 > x0) {
x = (float) x1 + 800f;
} else
x = (float) x1 - 800f;
y = Math.round(yCoordinates.get(yCoordinates.size() - 1));
} else if (y1 != y0 && x1 == x0) {
if (y1 > y0) {
y = (float) Math.abs(y1) - 800f;
} else
y = (float) Math.abs(y1) + 800f;
x = Math.round(xCoordinates.get(xCoordinates.size() - 1));
} else {
float m = (float) (yCoordinates.get(yCoordinates.size() - 1) * (-1) - yCoordinates
.get(yCoordinates.size() - 2) * (-1))
/ (float) (xCoordinates.get(xCoordinates.size() - 1) - xCoordinates
.get(xCoordinates.size() - 2));
if (x1 > x0) {
x = (float) ((float) x1 + 800f / (float) Math
.sqrt((double) ((double) 1f + (double) (m * m))));
} else
x = (float) ((float) x1 - 800f / (float) Math
.sqrt((double) ((double) 1f + (double) (m * m))));
if (y0 > y1) {
y = (float) ((float) Math.abs(y1) + 800f / (float) Math
.sqrt((double) (((double) 1f / (double) (m * m)) + (double) 1f)));
} else
y = (float) ((float) Math.abs(y1) - 800f / (float) Math
.sqrt((double) (((double) 1f / (double) (m * m)) + (double) 1f)));
}
xCoordinates.add(x);
yCoordinates.add(y);
}

2D Euclidean vector rotations

I have a euclidean vector a sitting at the coordinates (0, 1).
I want to rotate a by 90 degrees (clockwise) around the origin: (0, 0).
If I have a proper understanding of how this should work, the resultant (x, y) coordinates after the rotation should be (1, 0).
If I were to rotate it by 45 degrees (still clockwise) instead, I would have expected the resultant coordinates to be (0.707, 0.707).
theta = deg2rad(angle);
cs = cos(theta);
sn = sin(theta);
x = x * cs - y * sn;
y = x * sn + y * cs;
Using the above code, with an angle value of 90.0 degrees, the resultant coordinates are: (-1, 1).
And I am so damn confused.
The examples seen in the following links represent the same formula shown above surely?
What have I done wrong?
Or have I misunderstood how a vector is to be rotated?
Rotating a vector 90 degrees is particularily simple.
(x, y) rotated 90 degrees around (0, 0) is (-y, x).
If you want to rotate clockwise, you simply do it the other way around, getting (y, -x).
you should remove the vars from the function:
x = x * cs - y * sn; // now x is something different than original vector x
y = x * sn + y * cs;
create new coordinates becomes, to avoid calculation of x before it reaches the second line:
px = x * cs - y * sn;
py = x * sn + y * cs;
Rotate by 90 degress around 0,0:
x' = -y
y' = x
Rotate by 90 degress around px,py:
x' = -(y - py) + px
y' = (x - px) + py
Sounds easier to do with the standard classes:
std::complex<double> vecA(0,1);
std::complex<double> i(0,1); // 90 degrees
std::complex<double> r45(sqrt(2.0),sqrt(2.0));
vecA *= i;
vecA *= r45;
Vector rotation is a subset of complex multiplication. To rotate over an angle alpha, you multiply by std::complex<double> { cos(alpha), sin(alpha) }
You're calculating the y-part of your new coordinate based on the 'new' x-part of the new coordinate. Basically this means your calculating the new output in terms of the new output...
Try to rewrite in terms of input and output:
vector2<double> multiply( vector2<double> input, double cs, double sn ) {
vector2<double> result;
result.x = input.x * cs - input.y * sn;
result.y = input.x * sn + input.y * cs;
return result;
}
Then you can do this:
vector2<double> input(0,1);
vector2<double> transformed = multiply( input, cs, sn );
Note how choosing proper names for your variables can avoid this problem alltogether!

(C++) Need to figure out all points within a radius using reg. 2D windows coord. system

Sorry in advance, I'm struggling a bit with how to explain this... :)
Essentially, I've got a typical windows coordinate system (the Top, Left is 0,0). If anybody's familiar with the haversine query, like in SQL, it can get all points in a radius based on latitude and longitude coordinates.
I need something much simpler, but my math skills ain't all up to par! Basically, I've got random points scattered throughout about a 600x400 space. I have a need to, for any X,Y point on the map, run a query to determine how many other points are within a given radius of that one.
If that's not descriptive enough, just let me know!
Straightforward approach:
You can calculate the distance between to points using the Pythagorean theorem:
deltaX = x1 - x2
deltaY = y1 - y2
distance = square root of (deltaX * deltaX + deltaY * deltaY)
Given point x1,y1, do this for every other point (x2,y2) to see if the calculated distance is within (less than or equal to) your radius.
If you want to make it speedier, calculate and store the square of the radius and just compare against (deltaX * deltaX + deltaY * deltaY), avoiding the square root.
Before doing the Pythagoras, you could also quickly eliminate any point that falls outside of the square that can fully contain the target circle.
// Is (x1, y1) in the circle defined by center (x,y) and radius r
bool IsPointInCircle(x1, y1, x, y, r)
{
if (x1 < x-r || x1 > x+r)
return false;
if (y1 < y-r || y1 > y+r)
return false;
return (x1-x)*(x1-x) + (y1-y)*(y1-y) <= r*r
}
Use Pythagoras:
distance = sqrt(xDifference^2 + yDifference^2)
Note that '^' in this example means "to the power of" and not C's bitwise XOR operator. In other words the idea is to square both differences.
If you only care about relative distance you shouldn't use square root you can do something like:
rSquared = radius * radius #square the radius
foreach x, y in Points do
dX = (x - centerX) * (x - centerX) #delta X
dY = (y - centerY) * (y - centerY) #delta Y
if ( dX + dY <= rSquared ) then
#Point is within Circle
end
end
Using the equation for a circle:
radius ** 2 = (x - centerX) ** 2 + (y - centerY) ** 2
We want to find if a point (x, y) is inside of the circle. We perform the test using this equation:
radius ** 2 < (x - centerX) ** 2 + (y - centerY) ** 2
// (Or use <= if you want the circumference of the circle to be included as well)
Simply substitute your values into that equation. If it works (the inequality is true), the point is inside of the circle. Otherwise, it isn't.

Creating a linear gradient in 2D array

I have a 2D bitmap-like array of let's say 500*500 values. I'm trying to create a linear gradient on the array, so the resulting bitmap would look something like this (in grayscale):
(source: showandtell-graphics.com)
The input would be the array to fill, two points (like the starting and ending point for the Gradient tool in Photoshop/GIMP) and the range of values which would be used.
My current best result is this:
alt text http://img222.imageshack.us/img222/1733/gradientfe3.png
...which is nowhere near what I would like to achieve. It looks more like a radial gradient.
What is the simplest way to create such a gradient? I'm going to implement it in C++, but I would like some general algorithm.
This is really a math question, so it might be debatable whether it really "belongs" on Stack Overflow, but anyway: you need to project the coordinates of each point in the image onto the axis of your gradient and use that coordinate to determine the color.
Mathematically, what I mean is:
Say your starting point is (x1, y1) and your ending point is (x2, y2)
Compute A = (x2 - x1) and B = (y2 - y1)
Calculate C1 = A * x1 + B * y1 for the starting point and C2 = A * x2 + B * y2 for the ending point (C2 should be larger than C1)
For each point in the image, calculate C = A * x + B * y
If C <= C1, use the starting color; if C >= C2, use the ending color; otherwise, use a weighted average:
(start_color * (C2 - C) + end_color * (C - C1))/(C2 - C1)
I did some quick tests to check that this basically worked.
In your example image, it looks like you have a radial gradient. Here's my impromtu math explanation for the steps you'll need. Sorry for the math, the other answers are better in terms of implementation.
Define a linear function (like y = x + 1) with the domain (i.e. x) being from the colour you want to start with to the colour your want to end with. You can think of this in terms of a range the within Ox0 to OxFFFFFF (for 24 bit colour). If you want to handle things like brightness, you'll have to do some tricks with the range (i.e. the y value).
Next you need to map a vector across the matrix you have, as this defines the direction that the colours will change in. Also, the colour values defined by your linear function will be assigned at each point along the vector. The start and end point of the vector also define the min and max of the domain in 1. You can think of the vector as one line of your gradient.
For each cell in the matrix, colours can be assigned a value from the vector where a perpendicular line from the cell intersects the vector. See the diagram below where c is the position of the cell and . is the the point of intersection. If you pretend that the colour at . is Red, then that's what you'll assign to the cell.
|
c
|
|
Vect:____.______________
|
|
I'll just post my solution.
int ColourAt( int x, int y )
{
float imageX = (float)x / (float)BUFFER_WIDTH;
float imageY = (float)y / (float)BUFFER_WIDTH;
float xS = xStart / (float)BUFFER_WIDTH;
float yS = yStart / (float)BUFFER_WIDTH;
float xE = xEnd / (float)BUFFER_WIDTH;
float yE = yEnd / (float)BUFFER_WIDTH;
float xD = xE - xS;
float yD = yE - yS;
float mod = 1.0f / ( xD * xD + yD * yD );
float gradPos = ( ( imageX - xS ) * xD + ( imageY - yS ) * yD ) * mod;
float mag = gradPos > 0 ? gradPos < 1.0f ? gradPos : 1.0f : 0.0f;
int colour = (int)( 255 * mag );
colour |= ( colour << 16 ) + ( colour << 8 );
return colour;
}
For speed ups, cache the derived "direction" values (hint: premultiply by the mag).
There are two parts to this problem.
Given two colors A and B and some percentage p, determine what color lies p 'percent of the way' from A to B.
Given a point on a plane, find the orthogonal projection of that point onto a given line.
The given line in part 2 is your gradient line. Given any point P, project it onto the gradient line. Let's say its projection is R. Then figure out how far R is from the starting point of your gradient segment, as a percentage of the length of the gradient segment. Use this percentage in your function from part 1 above. That's the color P should be.
Note that, contrary to what other people have said, you can't just view your colors as regular numbers in your function from part 1. That will almost certainly not do what you want. What you do depends on the color space you are using. If you want an RGB gradient, then you have to look at the red, green, and blue color components separately.
For example, if you want a color "halfway between" pure red and blue, then in hex notation you are dealing with
ff 00 00
and
00 00 ff
Probably the color you want is something like
80 00 80
which is a nice purple color. You have to average out each color component separately. If you try to just average the hex numbers 0xff0000 and 0x0000ff directly, you get 0x7F807F, which is a medium gray. I'm guessing this explains at least part of the problem with your picture above.
Alternatively if you are in the HSV color space, you may want to adjust the hue component only, and leave the others as they are.
void Image::fillGradient(const SColor& colorA, const SColor& colorB,
const Point2i& from, const Point2i& to)
{
Point2f dir = to - from;
if(to == from)
dir.x = width - 1; // horizontal gradient
dir *= 1.0f / dir.lengthQ2(); // 1.0 / (dir.x * dir.x + dir.y * dir.y)
float default_kx = float(-from.x) * dir.x;
float kx = default_kx;
float ky = float(-from.y) * dir.y;
uint8_t* cur_pixel = base; // array of rgba pixels
for(int32_t h = 0; h < height; h++)
{
for(int32_t w = 0; w < width; w++)
{
float k = std::clamp(kx + ky, 0.0f, 1.0f);
*(cur_pixel++) = colorA.r * (1.0 - k) + colorB.r * k;
*(cur_pixel++) = colorA.g * (1.0 - k) + colorB.g * k;
*(cur_pixel++) = colorA.b * (1.0 - k) + colorB.b * k;
*(cur_pixel++) = colorA.a * (1.0 - k) + colorB.a * k;
kx += dir.x;
}
kx = default_kx;
ky += dir.y;
}
}