1

I'm building a function at the moment in C++ that will let me create a directional ray in my 3D application when I click on the screen. I'm working on some x's and y's calculation at the moment, but the problem is that I do a std::cout on x and y, the values stay the same. If I remove the static keyword this works fine, but I want to keep it as a static local variable as I will be using this function many times, so what exactly is the problem or what exactly am I doing wrong that's making it print the same value out all the time?

Heres the function:

void Mouse::GetClickDirection(D3DXMATRIX projMatrix)
{
    static POINT mousePoint;
    GetCursorPos(&mousePoint);

    ScreenToClient(hwnd, &mousePoint);

    static float width = (float)backBufferWidth;
    static float height = (float)backBufferHeight;

    static float x = (2.0f * mousePoint.x / width - 1.0f) / projMatrix(0, 0);
    static float y = (-2.0f * mousePoint.y / height + 1.0f) / projMatrix(1,1);

    D3DXVECTOR3 origin(0.0f, 0.0f, 0.0f);
    D3DXVECTOR3 dir(x, y, 1.0f);

    system("CLS");
    std::cout << "X: " << x << std::endl;
    std::cout << "Y: " << y << std::endl;

}
4

4 に答える 4

2

That's exactly what static keyword means, variable gets initialized only once. From your code, your variables' values are only changed in the initializers, which are executed only once per program execution. As they are dependent on the parameter, they cannot be static. If you want to preserve the values dependent on the parameters, you need to mainain some form of cache, however, it could be even bigger overhead then initializing the variables with every function call.

于 2013-10-23T14:46:44.610 に答える
1

私の推測では、変数の定義と割り当てを分離する必要があります。

static float x;
static float y;
x = (2.0f * mousePoint.x / width - 1.0f) / projMatrix(0, 0);
y = (-2.0f * mousePoint.y / height + 1.0f) / projMatrix(1,1);

初期化は一度だけなので。

于 2013-10-23T14:56:01.953 に答える
0

それらを作らないでくださいstaticstaticローカル変数は、関数が最初に呼び出されたとき (正式には、実行が最初に初期化子を通過するときですが、このコードでは違いは関係ありません) に最大 1 回初期化されるため、その後の呼び出しでは古い値xを保持します。yこれらが静的である理由はありません。

于 2013-10-23T14:50:45.480 に答える