2

Given a cartesian position, how can you map the angle from the origin into the range 0 .. 1?

I have tried:

sweep = atan(pos.y,pos.x) + PI) / (2.*PI);

(where sweep should be between 0 and 1)

This is GLSL, so the atan function is happy with two parameters (y then x) and returns -PI ... PI

This gives 1 in the top-left quadrant, a nice gradient in the top-right going round to the bottom right quadrant and then 0 in the bottom left quadrant:

A badly mapped atan

How do I get a nice single gradient sweep instead? I want the maximum sweep somewhere, and the minimum adjacent to it anti-clockwise.

Here's my GLSL shader code:

Vertex shader:

uniform mat4 MVP_MATRIX;
attribute vec2 VERTEX;
varying vec2 pos;
void main() {
    gl_Position = MVP_MATRIX * vec4(VERTEX,-2,1.);
    pos = gl_Position.xy;
}

Fragment shader:

uniform vec4 COLOUR;
varying vec2 pos;
void main() {
    float PI = 3.14159265358979323846264;
    float sweep = (atan(pos.y,pos.x) + PI) / (2.*PI);
    gl_FragColor = vec4(COLOUR.rgb * sweep,COLOUR.a);
}
4

2 に答える 2

7

ほとんどのプログラミング言語には、2パラメータバージョンのがありますatanatan2これは通常、(-PI、PI]の範囲の結果を返します。これを値0-1に変換するには、次を使用できます。

(atan2(y,x) + PI) / (2*PI)

あなたの言語のatan関数は2つの引数を取るので、おそらく。と同じことをしatan2ます。

于 2012-05-16T13:24:52.397 に答える
3

atan2(-pi、pi)で角度を返すを使用しているようです。次のようにします。

atan2(pos.y,pos.x) + PI) / (2*PI)
于 2012-05-16T13:25:36.837 に答える