Algorithm to rotate arbitrary gradient 90 degrees either way
I'm attempting some rudimentary ray tracing and I have a 2D gradient (called dybydx). I trace from the centre of a square, 0.5, 0.5, and would like to set additional traces normal to the gradient to increase the field of observation (by ~< 0.5). I'm fairly new to fp arithmetic and this is causing some head scratching when I debug.
I hope the following code explains the rest:
if (incX) {
if (incY) {
if (cclockwise) {
x -= System::Math::Sin(theta) / 2;
y += System::Math::Cos(theta) / 2;
} else {
x += System::Math::Sin(theta) / 2;
y -= System::Math::Cos(theta) / 2;
}
} else {
if (cclockwise) {
x += System::Math::Cos(theta) / 2;
y += System::Math::Sin(theta) / 2;
} else {
x -= System::Math::Cos(theta) / 2;
y -= System::Math::Sin(theta) / 2;
}
}
} else {
if (incY) {
if (cclockwise) {
x -= System::Math:开发者_开发百科:Cos(theta) / 2;
y -= System::Math::Sin(theta) / 2;
} else {
x += System::Math::Cos(theta) / 2;
y += System::Math::Sin(theta) / 2;
}
} else {
if (cclockwise) {
x += System::Math::Sin(theta) / 2;
y -= System::Math::Cos(theta) / 2;
} else {
x -= System::Math::Sin(theta) / 2;
y += System::Math::Cos(theta) / 2;
}
}
}
I've been round and round the quadrants on paper but I forgot Windows reverses the conventional y-axis (hence what I thought was clockwise isn't, but that is an arbitrary error and unimportant). What I really would like, is a fool-proof way to rotate my gradient 90 degrees either way. Thanks.
edit-- theta is the angle from horizontal to the +ve y axies that the gradient makes (on paper).
edit-- incX and incY mean the original gradient (really, really) is increasing in X and Y respectively.
if you substitue 90 degrees in @dario_ramos equation you get:
x' = -y
y' = x
Btw if you ever draw this on a checked paper you'll see why it's so trivial.
The general formula is:
x' = x cos(theta) - y sin(theta)
y' = x sin(theta) + y cos(theta)
You don't need to use a flag for the orientation: the fact that it is clockwise or counterclockwise is represented by the sign of theta, you define that. For example, define that a positive theta means counterclokwise. The formula considers both cases
Edit: Go with yi_H's solution if you only wish to rotate 90 degrees; it's more efficient, since cos() and sin() are cpu-expensive in comparison
精彩评论