Pregunta

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;

}
¿Fue útil?

Solución

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.

Otros consejos

There is no reason to use static variables here.

Once a local static has been initialized, it isn't updated unless you explicitly assign new values to it.
And what you're doing is initialization, not assignment.

If you're worried about efficiency, it's most likely less efficient to use local statics - they need at least an initialization check (on each function call) and possibly a cache miss or two to fetch the values.

My guess is that you have to separate variable definition and assignment:

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);

Because initialization is made only once.

Don't make them static. static local variables are initialized at most once, when the function is first called (formally, when execution first passes through the initializer, but the difference isn't relevant in this code), so on subsequent calls x and y keep their old values. There's no reason for these to be static.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top